#!/usr/bin/perl
#
# Move Construction Spaces from /home/$user/public_html
# to /home/httpd/html/priv/$domain/$user and vice versa
# 

use strict;
use lib '/home/httpd/lib/perl/';
use LONCAPA::Configuration;
use LONCAPA qw(:DEFAULT :match);
use Apache::lonlocal;
use File::Copy;
use GDBM_File;

my $lang = &Apache::lonlocal::choose_language();
&Apache::lonlocal::get_language_handle(undef,$lang);

if ($< != 0) {
    print(&mt('You must be root in order to move Construction Spaces.').
         "\n");
    exit;
}

my $perlvar=&LONCAPA::Configuration::read_conf();
my ($lonuserdir,$londocroot);
if (ref($perlvar) eq 'HASH') {
    $lonuserdir = $perlvar->{'lonUsersDir'};
    $londocroot = $perlvar->{'lonDocRoot'};
}
undef($perlvar);

# Abort if more than one argument.

my $parameter=$ARGV[0];
$parameter =~ s/^\s+//;
$parameter =~ s/\s+$//;

if ((@ARGV > 1) || (($parameter ne '') && ($parameter !~ /^(move|undo)$/))) {
    print &mt('usage: [_1]','move_construction_spaces.pl [move|undo]')."\n\n".
          &mt('You should enter either no arguments, or just one argument -- either move or undo.')."\n".
          &mt("move - to move authors' Construction Spaces from: [_1] to [_2].",
              "'/home'","'$londocroot/priv/'")."\n".
          &mt('undo - to reverse those changes and move Construction Spaces back from: [_1] to [_2].',
              "'$londocroot/priv/'","'/home'")."\n".
          &mt('no argument to do a dry run of the move option, without actually moving anything.')."\n";
    exit;
}

print "\n".&mt("Moving authors' Construction Spaces.")."\n".
      "-----------------------------\n\n".
      &mt('If run without an argument, the script will report what it would do when moving Construction Spaces from [_1] to [_2].',
          "'/home'","'$londocroot/priv/'")."\n\n".
      &mt('If there are ambiguities (i.e., the same username belongs to two domains), this will be flagged, and you will be able to decide how to proceed.')."\n";

my $perlvar=&LONCAPA::Configuration::read_conf();
my ($lonuserdir,$londocroot);
if (ref($perlvar) eq 'HASH') {
    $lonuserdir = $perlvar->{'lonUsersDir'};
    $londocroot = $perlvar->{'lonDocRoot'};
}
undef($perlvar);

my (undef,undef,$uid,$gid) = getpwnam('www');
my ($action) = ($parameter=~/^(move|undo)$/);
if ($action eq '') {
    $action = 'dryrun';
}

if ($action eq 'dryrun') {
    print "\n".
          &mt('Running in exploratory mode.')."\n".
          &mt('Run with argument [_1] to actually move Construction Spaces to [_2], i.e., [_3]',
              "'move'","'$londocroot/priv'","\nperl move_construction_spaces.pl move")."\n\n".
          &mt('Run with argument [_1] to move Construction spaces back to [_2], i.e., [_3]',
              "'undo'","'/home'","\nperl move_construction_spaces.pl undo")."\n\n".
          &mt('Continue? ~[y/N~] ');
    if (!&get_user_selection()) {
        exit;
    }
} else {
    print "\n ***".&mt('Running in a mode where changes will be made.')."\n";
    if ($action eq 'move') {
        print "\n".
              &mt('Mode is [_1] -- directories will be moved to [_2].',
                  "'$action'","'$londocroot/priv'")."\n";
    } else {
        print "\n".
              &mt('Mode is [_1] -- directories will be moved back to [_2].',
                  "'$action'","'/home'")."\n";
    }
    print &mt('Continue? ~[y/N~] ');
    if (!&get_user_selection()) {
        exit;
    }
}

# Authors hosted on this server
my %allauthors;
my %pubusers;

if ($action eq 'move') {
    if (-d "$londocroot/priv") {
        print "\n".
              &mt('New Construction Spaces directory: [_1] already exists.',
                  "'$londocroot/priv'")."\n";
    } else {
        print "\n".
              &mt('Creating new directory: [_1] for Construction Spaces.',
                  "'$londocroot/priv'")."\n";
        if (mkdir("$londocroot/priv",0755)) {
            if (chown($uid,$gid,"$londocroot/priv")) {
                print &mt('Creation Successful')."\n";
            } else {
                print &mt('Failed to change ownership to [_1].',"'$uid:$gid'")."\n".
                &mt('Stopping')."\n";
                exit;
            }
        } else {
            print &mt('Failed to create directory [_1].',"'$londocroot/priv'")."\n".
                  &mt('Stopping')."\n";
            exit;
        }
    }
}

my @machinedoms;
if ($lonuserdir) {
    my $dir;
    if (opendir($dir,$lonuserdir)) {
        my @contents = (grep(!/^\.{1,2}$/,readdir($dir)));
        foreach my $item (@contents) {
            if (-d "$lonuserdir/$item") {
                if ($item =~ /^$match_domain$/) {
                    my $domain = $item;
                    unless (grep(/^\Q$domain\E$/,@machinedoms)) {
                        push(@machinedoms,$domain);  
                    }
                    my $dom_target="/home/httpd/html/priv/$domain";
                    if ($action eq 'move') {
                        if (!-e $dom_target) {
                            if (mkdir($dom_target,0755)) {
                                chown($uid,$gid,$dom_target);
                                print &mt('Made [_1].',"'$dom_target'")."\n";
                            } else {
                                print &mt('Failed to make [_1].',"'$dom_target'")."\n".
                                      &mt('Stopping')."\n";
                                exit;
                            }
                        } elsif ($action eq 'dryrun') {
                            print &mt('Would make [_1].',"'$dom_target'")."\n";
                        }
                    }
                    my %authors=();
                    my $fname = "$lonuserdir/$domain/nohist_domainroles.db";
                    my $dbref;
                    if (-e $fname) {
                        $dbref=&LONCAPA::locking_hash_tie($fname,&GDBM_READER());
                    }
                    if (!$dbref) {
                        print &mt('Unable to tie to [_1].',"'$fname'")."\n";
                    } elsif (ref($dbref) eq 'HASH') {
                        foreach my $key (keys(%{$dbref})) {
                            $key = &unescape($key);
                            if ($key =~ /^au\:($match_username)\Q:$domain\E/) {
                                push(@{$allauthors{$1}},$domain);
                            }
                        }
                        &LONCAPA::locking_hash_untie($dbref);
                    }
                }
            }
        }
        closedir($dir);
    } else {
        print &mt('Could not open [_1].',"'$lonuserdir'")."\n".
              &mt('Stopping')."\n";
        exit;
    }
}

if ($londocroot ne '') {
    if (-d "$londocroot/res") {
        my ($dir,$domdir);
        if (opendir($dir,"$londocroot/res")) {
            my @contents = (grep(!/^\.{1,2}$/,readdir($dir)));
            foreach my $dom (@contents) {
                if ((grep(/^\Q$dom\E/,@machinedoms)) && (-d "$londocroot/res/$dom")) {
                    if (opendir($domdir,"$londocroot/res/$dom")) {
                        my @unames = (grep(!/^\.{1,2}$/,readdir($domdir)));
                        foreach my $uname (@unames) {
                            if ($uname =~ /^$match_username$/) {
                                push(@{$pubusers{$uname}},$dom);
                            }
                        }
                    }
                }
            }
        }
    }
}

if ($action eq 'undo') {
    my %privspaces;
    if ($londocroot ne '') {
        if (-d "$londocroot/priv") {
            my ($dir,$domdir);
            if (opendir($dir,"$londocroot/priv")) {
                my @contents = (grep(!/^\.{1,2}/,readdir($dir)));
                foreach my $dom (@contents) {
                    next if (!-d "$londocroot/priv/$dom");
                    if (opendir($domdir,"$londocroot/priv/$dom")) {
                        my @unames = (grep(!/^\.{1,2}$/,readdir($domdir)));
                        foreach my $uname (@unames) {
                            if ($uname =~ /^$match_username$/) {
                                push(@{$privspaces{$uname}},$dom);
                            }
                        }
                    }
                }
            }
        }
    }
    foreach my $uname (keys(%privspaces)) {
        if (ref($privspaces{$uname}) eq 'ARRAY') {
            if (@{$privspaces{$uname}} > 1) {
                my $displaydoms = join(', ',@{$privspaces{$uname}});
                print &mt('Same username used for authors in multiple domains.')."\n".
                      &mt('This configuration is not supported where Construction Spaces are located in [_1].','/home').".\n".
                      &mt('You will be able to move files for just one of the domains, choose which one.')."\n".
                      &mt('The domains to choose from are: [_1].',"'$displaydoms'")."\n".
                      &mt('Enter choice: ');
                my $choice=<STDIN>;
                chomp($choice);
                if (grep(/^\Q$choice\E$/,@{$privspaces{$uname}})) {
                    &move_priv_to_home($londocroot,$uname,$choice);
                } else {
                    print &mt('Invalid choice of domain:')." $choice\n".
                          &mt('Skipping this user: [_1].',"'$uname'")."\n";
                    next;
                }
            } elsif (@{$privspaces{$uname}} == 1) {
                    &move_priv_to_home($londocroot,$uname,$privspaces{$uname}[0]);
            } else {
                print &mt('Username [_1] found in [_2] was not within a domain',
                          "'$uname'","'$londocroot/priv'")."\n";
            }
        }
    }
    print &mt('Done')."\n";
    exit;
}

# Iterate over directories in /home
if (opendir(my $dir,"/home")) {
    foreach my $item (grep(!/^\.{1,2}$/,readdir($dir))) {
        next if ($item eq 'www');
        if (-d "/home/$item") {
# Is there a public_html-directory?
            if (-d "/home/$item/public_html") {
                my $author = $item;
                my ($domain,$skipped);
                if (ref($pubusers{$author}) eq 'ARRAY') {
                    ($domain,$skipped) = &choose_domain($action,$author,$pubusers{$author});
                }
                if (($domain eq '') && (!$skipped)) {
                    if (ref($allauthors{$author}) eq 'ARRAY') {
                        ($domain,$skipped) = &choose_domain($action,$author,$allauthors{$author});
                    }
                }
                if ($domain) { 
                    my $source_path="/home/$author/public_html";
                    my $target_path="$londocroot/priv/$domain/$author";
                    if ($action eq 'move') {
                        move($source_path,$target_path);
                            chown($uid,$gid,$target_path);
                            chmod($target_path,0755);
                        print &mt('Moved [_1] to [_2].',"'$source_path'","'$target_path'")."\n";
                    } elsif ($action eq 'dryrun') {
                        print &mt('Would move [_1] to [_2].',"'$source_path'","'$target_path'")."\n";
                    }
                } elsif (!$skipped) {
                    print '*** '.&mt('WARNING: [_1] has no domain.',"'$author'")."\n".
                          &mt('Enter [_1]: do nothing, continue.','1')."\n".
                          &mt('Enter [_2]: stop.','2')."\n".
                          &mt('or enter domain for user to be placed into')."\n".
                          &mt('Your input: ');
                    my $choice=<STDIN>;
                    chomp($choice);
                    next if ($choice ==1);
                    if ($choice == 2) {
                        print &mt('Stopped.')."\n";
                        exit;
                    } 
                    if ($choice =~ /^$match_domain$/) {
                        my $dompath="$londocroot/priv/$choice";
                        my $newpath="$londocroot/priv/$choice/$author";
                        unless (-e $dompath) {
                            print '*** '.&mt('WARNING: [_1] does not yet exist.',"'$dompath'")."\n";
                        }
                        if ($action eq 'move') {
                            print &mt('Making author [_1] in domain [_2].',"'$author'","'$choice'")."\n";
                            unless (-e $dompath) {
                                print &mt('Making [_1].',"'$dompath'")."\n";
                                mkdir($dompath,0755);
                                chown($uid,$gid,$dompath);
                            }
                            print &mt('Making [_1].',"'$newpath'")."\n";
                            mkdir($newpath,0755);
                            chown($uid,$gid,$newpath);
                        } elsif ($action eq 'dryrun') {
                           print &mt('Would make author [_1] in domain [_2].',"'$author'","'$choice'")."\n";
                           unless (-e $dompath) {
                               print &mt('Would make [_1].',"'$dompath'")."\n";
                           }
                           print &mt('Would make [_1].',"'$newpath'")."\n";
                        }
                    }
                }
            }
        }
    }
}
print "\nDone.\n";

sub choose_domain { 
    my ($action,$author,$domarrayref) = @_;
    my ($domain,$skipped);
    if (ref($domarrayref) eq 'ARRAY') {
         if (@{$domarrayref} > 1) {
             print '*** '.&mt('ERROR: [_1] found in multiple domains.',"'$author'")."\n".
                   &mt('Enter a number to choose what action to take.')."\n";
             my $num = 1;
             for (my $i=0; $i<@{$domarrayref}; $i++) {
                 print &mt('To use: [_1] enter [_2].',$domarrayref->[$i],$num)."\n";
                 $num ++;
             }
             print &mt('To skip this user enter: [_1].',$num)."\n".
                   &mt('Your choice:').' ';
             my $choice=<STDIN>;
             chomp($choice);
             if ($choice =~ /^\d+$/) {
                 if (($choice == $num) || ($choice > $num)) {
                     $skipped = 1;       
                 } elsif (($choice < $num) && ($choice > 0)) {
                     $domain = $domarrayref->[$choice-1];
                 } else {
                     print &mt('Invalid choice:')." $choice\n";
                     $skipped = 1;
                 }
             } else {
                 print &mt('Invalid choice:')." $choice\n";
                 $skipped = 1;
             }
         } elsif (@{$domarrayref} == 1) {
             $domain = $domarrayref->[0];
         }
    }
    return ($domain,$skipped);
}

sub move_priv_to_home {
    my ($londocroot,$uname,$domain) = @_;
    if ($uname =~ /^$match_username$/ && $domain =~ /^$match_domain$/) {
        my $source_path="$londocroot/priv/$domain/$uname";
        my $target_path="/home/$uname/public_html";
        if (!-e "/home/$uname") {
            if (mkdir("/home/$uname",0755)) {
                chown($uid,$gid,"/home/$uname");
            } else {
                print &mt('Failed to create directory [_1] -- not moving [_2].',
                          "'/home/$uname'","'$source_path'")."\n";
            }
        }
        if (!-e $target_path) {
             move($source_path,$target_path);
             chown($uid,$gid,$target_path);
             chmod($target_path,0755);
             print &mt('Moved [_1] to [_2].',"'$source_path'","'$target_path'")."\n";
        } else {
             print &mt('Directory [_1] already exists -- not moving [_2].',
                       "'$target_path'","'$source_path'")."\n";
        }
    }
    return;
}

sub get_user_selection {
    my ($defaultrun) = @_;
    my $do_action = 0;
    my $choice = <STDIN>;
    chomp($choice);
    $choice =~ s/(^\s+|\s+$)//g;
    my $yes = &mt('y');
    if ($defaultrun) {
        if (($choice eq '') || ($choice =~ /^\Q$yes\E/i)) {
            $do_action = 1;
        }
    } else {
        if ($choice =~ /^\Q$yes\E/i) {
            $do_action = 1;
        }
    }
    return $do_action;
}

