#!/usr/bin/perl
# moveuser: move a user to another home partition.
# $Id: moveuser,v 1.39 2014/11/20 19:53:57 jjones Exp $

use strict;
use warnings;
use Getopt::Long;
use HTML::FormatText;
use Data::Dumper;
use Fcntl qw(O_WRONLY);
use Sys::Hostname;

my $pkg = bless { immutables => \@_ }, __PACKAGE__;
$pkg->main();

# Percent used space for destination after migration
sub space_threshold { 80 }

sub main {
    my $self = shift;
    #die "$0: This script temporarily disabled, contact jjones\@bluehost.com if you don't like this";
    my ( $user, $target, $mail, $buffer, $BUFF, $stdout );
    my $foreground = 0;
    my $immutables = 0;
    my $meshuggah_for_life = GetOptions(
        "user=s"            => \$user,
        "target|dest=s"     => \$target,
        "mailto|email=s"    => \$mail,
        "foreground"        => \$foreground,
        "checkimmutables"   => \$immutables,
    );
    unless ( $user && $target ) {
        print $self->usage();
        exit;
    }
    die "No user specified!\n"   if ( !$user );
    die "No target specified!\n" if ( !$target );
    my $current = ( getpwnam($user) )[7];
    die "I can't find the user $user!\n" if ( !$current );
    my %parts       = ();
    my $mounts      = do { local ( @ARGV, $/ ) = '/proc/mounts'; <> };
    my @mounts_list = split( /\n/, $mounts );

    foreach my $mount (@mounts_list) {
        if ( $mount =~ m{^.*\s(/home\d+)} ) {
            $parts{$1} = 1;
        }
    }
    die "$target is not a valid partition or is not mounted!\n" unless ( $parts{$target} );
    if ($mail) {
        $stdout = select;
        $|      = 1;
        open $BUFF, ">", \$buffer;
        select $BUFF;
    }
    if ( $immutables and my $immutable_files = $self->chk_immutables($current) ) {
        print "Error: $current has one or more immutable inodes!! Refusing to continue.\n",
          "Please review and correct these problems before continuing\n",
          Dumper($immutable_files);
        if ($mail) {
            close $BUFF;
            select $stdout;
            $| = 1;
            $self->send_mail( $mail, $user, $buffer );
        }
        exit(42);
        return;
    }
    chdir "/usr/local/cpanel/whostmgr/docroot";
    $ENV{'GATEWAY_INTERFACE'} = "CGI/1.1";
    $ENV{'QUERY_STRING'}      = "user=$user&mnt=$target";
    $ENV{'REQUEST_METHOD'}    = 'GET';
    $ENV{'SCRIPT_URI'}        = '/scripts/dorearrange';
    $ENV{'REQUEST_URI'}       = '/scripts/dorearrange';
    $ENV{'CPANEL'}            = 'active';
    $ENV{'REMOTE_USER'}       = 'root';

    # Move old home out of the way
    my @pw = getpwnam $user;
    my $oldhome = $pw[7] or die "$user: no home";
    (my $source = $oldhome) =~ s{(/home\d*)/\w+$}{$1} or die "$user: unrecognized home";
    mkdir "$source/GRAVEYARD", 0700 unless -d "$source/GRAVEYARD";
    chmod 0700, "$source/GRAVEYARD" or die "$source/GRAVEYARD: chmod: $!";
    mkdir "$source/MOVEUSER", 0700 unless -d "$source/MOVEUSER";
    chmod 0700, "$source/MOVEUSER" or die "$source/MOVEUSER: chmod: $!";
    !lstat "$source/MOVEUSER/$user" or die "$source/MOVEUSER/$user: Already exists? Premature abortion!";
    $oldhome =~ m{^\Q$target\E/} and die "Already moved? homedir=$oldhome --user=$user --target=$target\n";
    rename $oldhome, "$source/MOVEUSER/$user" or die "$source/MOVEUSER/$user: Failed to mv: $!";

    # Create a naked bait home dir for dorearrange to consume
    mkdir $oldhome, 0755;
    -d $oldhome or die "$oldhome: Unable to mkdir: $!";
    chown $pw[2], $pw[3], $oldhome; # uid, gid, home

    # Run the actual migration (should be fairly quick since the home is empty)
    my $hft         = HTML::FormatText->new();
    my $dorearrange = `/usr/local/cpanel/whostmgr/bin/whostmgr ./dorearrange` . "\n\n";
    my $hft_text    = $hft->format_string($dorearrange);
    print "$hft_text\n";
    my $newhome = ( getpwnam($user) )[7];

    if ( -l "/home/$user" && $newhome ne ( split( ' ', `ls -dl /ramdisk/home/$user` ) )[10] ) {
        print "\nfixing /home/$user -> $newhome\n";
        unlink "/ramdisk/home/$user" || print "Can't remove /ramdisk/home/$user:  $!\n";
        system("ln -sf $newhome /ramdisk/home/$user") == 0 or print "failed: $!\n";
    }
    if ( !-l "/home/$user" ) {
        print "Creating /home/$user...\n";
        system("ln -sf $newhome /ramdisk/home/$user") == 0 or print "failed: $!\n";
    }
    if ( !-l "$source/$user" ) {
        print "Creating $source/$user...\n";
        system("ln -sf $newhome $source/.") == 0 or print "failed: $!\n";
    }
    system("chown -h $user $source/$user") == 0 or print "chown failed: $!\n";
    foreach my $file ( "$user", "passwd.vhosts" ) {
        my $f = "/etc/proftpd/$file";
        if ( -e $f ) {
            my $c = do { local ( @ARGV, $/ ) = $f; <> };
            print "Fixing $f\n";
            open( my $FILE, ">", $f );
            foreach my $line ( split( /\n/, $c ) ) {
                $line =~ s{:/home.*/$user\b}{:/home/$user};
                print $FILE $line, "\n";
            }
            close $FILE;
        }
    }

    # Slowly copy old homedir over to the new location
    my $move_cmd = qq{
        cd / ;
        tar -C $source/MOVEUSER/$user/. -cf - . |
          tar -C $newhome/. -xf - ;
        [ -d $source/GRAVEYARD/$user ] &&
          mv $source/GRAVEYARD/$user $source/GRAVEYARD/$user.$$ ;
        mv $source/MOVEUSER/$user $source/GRAVEYARD/. &&
          rm -rf $source/GRAVEYARD/$user 2>/dev/null ;
        [ -d $source/GRAVEYARD/$user ] &&
          (cd $source/GRAVEYARD/$user ;
           lsattr -a -R . 2>/dev/null |
             perl -n -e 'system "chattr", "+i", "$newhome/\$1"
               if /^\\S*i\\S*\\s+(.+)/' ) ;
        chattr -R -i $source/GRAVEYARD/$user* 2>/dev/null &&
          rm -rf $source/GRAVEYARD/$user* 2>/dev/null ;
    };
    if ($foreground) {
        # Desire to keep everything running in the foreground
        my $move_homedir = `($move_cmd) 2>&1`;
        chomp($move_homedir);
        print "$move_homedir\n";
    }
    else {
        # Desire to move the homedir in the background.
        if (!fork) {
            # Child does all the work in the background
            open STDIN,  "</dev/null";
            open STDOUT, ">/dev/null";
            open STDERR, ">/dev/null";
            # NOTE: Using 'system' instead of 'exec' in order to keep the 'moveuser' process in the ps output until the tar is done
            system "($move_cmd) 2>&1";
            exit;
        }
        # Parent process continues on...
    }

    if ($mail) {
        close $BUFF;
        select $stdout;
        $| = 1;
        $self->send_mail( $mail, $user, $buffer );
    }
}

sub send_mail {
    my $self       = shift;
    my $mailto     = shift;
    my $moved_user = shift;
    my $buffer     = shift;
    my $hostname   = Sys::Hostname::hostname;
    my $from       = 'root@' . $hostname;
    my $subject    = "$0: $moved_user results";
    #my $dump       = $self->dump_results($buffer);
    open my $SM, '|-', '/usr/sbin/sendmail -t';

    print $SM "To: $mailto\n";
    print $SM "From: $from\n";
    print $SM "Subject: $subject\n\n";
    print $SM qq{
        $mailto
        The user $moved_user migration process has completed.
        Please review the following results for any problems.
        $0 Result:
        $buffer;
    };

    close($SM);

}

sub dump_results {
    my $self = shift;
    my @data = @_;
    my $dump = Data::Dumper->new( [@data] );
    return $dump->Dump;
}

sub usage {
    my $self = shift;
    my $email = getlogin() || 'you';
    $email .= '@bluehost.com';
    my $spew = <<USAGE;

    Usage: $0 --user=custunam --target=\/home999 [ --mailto=$email ] [ <flags> ]

    --user and --target are required. These were \$ARGV[0] and \$ARGV[1] in prior revisons.
    --mailto emails results to the given address. Useful for backgrounding the process. (*)
    Flags:
    --foreground option will force the entire move to complete before releasing control.
    --checkimmutables will brute scan for all immutable files before moving. (not recommended)

    Aliases:
    --dest is an alias for --target
    --email and --em are aliases for --mailto
    -c is an alias for --checkimmutables
    -f is an alias for --foreground

    (*) Specifying the optional --mailto parameter will not print any result to STDOUT.

USAGE
    return $spew;
}

sub chk_immutables {
    my $self   = shift;
    my @nodes  = @_;      # Dirs/Files/Links/etc
    my %status = ();
    foreach my $node (@nodes) {
        if ( -l $node ) {    # is symbolic link
            #Do Nothing for Now
        }
        elsif ( -f $node ) {    # is a file
            if ( $self->sysopen_chk($node) ) {
                $status{$node} = $node;
            }
        }
        elsif ( -d $node ) {    # is a directory
            if ( opendir( my $DIR, $node ) ) {
                my $dir   = $node;
                my @files = readdir($DIR);
                closedir($DIR);
                my $result = $self->chk_immutables( map { "$dir/$_" } grep { !/^\.\.?$/ } @files );
                $status{$node} = $node if $result;
            }
            else {
                push @{ $self->{'immutables'} }, "Could not open dir $node ($!)";
            }
        }
    }
    foreach my $s ( keys %status ) {
        push @{ $self->{'immutables'} }, $s;
    }

    return @{ $self->{'immutables'} } ? $self->{'immutables'} : 0;
}

sub sysopen_chk {
    my $self          = shift;
    my $file          = shift;
    my $immutable_chk = eval {
        sysopen( my $FH, $file, O_WRONLY ) || die "Sysopen Fail $file: $!";
        close $FH;
    };
    if ($@) {
        warn "Could not sysopen $file: $@\n";
        return $file;
    }
    return 0;
}

