#!/usr/bin/perl -w

use strict;
use Fcntl ':mode';
use IO::Dirent;
use Getopt::Long;
umask 0000;
#use Data::Dumper;

#hardlinker
#arg 1 source dir (read-only)
#arg 2 dst dir (will make changes)
#arg 3 logs to look at (optional)

my ($host,$partition,$user,$type);
GetOptions ("host=s"		=> \$host,
            "partition=s"	=> \$partition,
            "user=s"		=> \$user,
            "type=s"		=> \$type),
  or die("Error in command line arguments\n");
die "Invalid partition $partition for $host\n" if ( !-d "/home/$host/$partition");
die "Invalid type $type\n" if ( $type !~ m/(daily|weekly|monthly|bimonthly)/ );

my $dst = "/home/$host/$partition/cpbackup/seed/$user";
my $src = "/home/$host/$partition/cpbackup/$type/$user";

if(! -d $src){
  print "$src was specified as the source but it doesn't exist!\n";
  exit;
}
print "SRC: $src\n";
print "DST: $dst\n";

my %DEBUG;
$DEBUG{LINK} = 0;
$DEBUG{MKDIR} = 0;
$DEBUG{CHOWN} = 0;
$DEBUG{UNLINK} = 0;
$DEBUG{RMDIR} = 0;
$DEBUG{PROGRESS} = 0;

#should keep us from actually creating/deleteing/modifying anything!
my $READONLY = 0;

my @srca = lstat($src);
my @dsta = lstat($dst);
#print Dumper(@srca);
#print Dumper(@dsta);

#if no destination we must be doing an initial hardlink session
unless(@dsta){
  print "$dst doesn't exist!\n" if $DEBUG{PROGRESS};
  my @dir = split('/', $dst);
  pop(@dir);
  my $d = join('/',@dir); 
  my @dstb = lstat ($d);
  if($srca[0] != $dstb[0]){
    print "$src and parent dir $d are not the same filesystem\n" if  $DEBUG{PROGRESS};
    exit;
  }
  recursivecompare("",$srca[2],$srca[4],$srca[5],$srca[9]);
  exit;
}

if($srca[0] != $dsta[0]){
  print "$src and $dst are not the same filesystem\n" if  $DEBUG{PROGRESS};
  exit;
}
recursivecompare("",$srca[2],$srca[4],$srca[5],$srca[9],$dsta[2],$dsta[4],$dsta[5],$dsta[9] );

#subs only below this line!

sub recursivecompare {
# 1 dir
# 2 source mode
# 3 source user
# 4 source group
# 5 source mtime
# 6 dst mode
# 7 dst user
# 8 dst group
# 9 dst mtime
  my $dir = shift;
  my $s_mode = shift;
  my $s_uid = shift;
  my $s_gid = shift;
  my $s_mtime = shift;
  my $d_mode = shift;
  my $d_uid = shift;
  my $d_gid = shift;
  my $d_mtime = shift;
  my $mode = sprintf("%o", ($s_mode&07777));
  my $oct_mode = '0'.$mode;
  my $oct = oct($oct_mode);

  print "recursively comparing $dir\n" if $DEBUG{PROGRESS};

  #fill d_mode if it exists might cause double stat, but only if we aren't called with the info we need
  if(! $d_mode){
    my @dsta = lstat("$dst/$dir");
    $d_mode = $dsta[2];
    $d_uid = $dsta[4];
    $d_gid = $dsta[5];
    $d_mtime = $dsta[9];
  }

  #does the directory exist or not?
  if(! $d_mode){
    #no, then create it
    print "making directory $dir\n" if $DEBUG{MKDIR};
    mkdir("$dst/$dir", $oct) unless $READONLY;
    print "chown $dir\n" if $DEBUG{CHOWN};
    chown $s_uid,$s_gid, "$dst/$dir";
  }else{
    #yes, so let's compare stats and fix
    if($s_uid != $d_uid or $s_gid != $d_gid){
      print "chown $dir\n" if $DEBUG{CHOWN};
      chown $s_uid,$s_gid, "$dst/$dir" unless $READONLY;
    }
    if($s_mode != $d_mode){
      print "chmod $dir\n" if $DEBUG{CHOWN};
      chmod $oct, "$dst/$dir" unless $READONLY;
    }
    if($s_mtime != $d_mtime){
      print "utime $dir\n" if $DEBUG{UTIME};
      utime $s_mtime, $s_mtime, "$dst/$dir";
    }
  }

  #handle the entries in the directory
  my %seen;
  #fill source ent
  opendir(SRC,"$src/$dir");
  my @srcent = readdirent(SRC);
  closedir(SRC);
  #if we didn't create the destination folder
  my %dhash;
  my @dstent;
  if($d_mode){
    opendir(DST,"$dst/$dir");
    @dstent = readdirent(DST);
    closedir(DST);
    %dhash = map { $dstent[$_]->{name} => $_ } 0 .. $#dstent;
    #fill file types if needed
    foreach my $ent (sort { $$a{'inode'} <=> $$b{'inode'}} @dstent){
      next if ($ent->{name} =~ /^\.\.?$/);
      fillstats("$dst/$dir/".$ent->{name}, \$ent) if($ent->{type} == 0);
    } 
  }
  #read through all in the source
  my $count = 0;
  foreach my $ent (sort { $$a{'inode'} <=> $$b{'inode'}} @srcent){
    if ( $count > 1000 ) {
      sleep 5;
      $count = 0;
    } else {
      $count++;
    }
    $seen{$ent->{name}} = 1;
    next if ($ent->{name} =~ /^\.\.?$/);
    fillstats("$src/$dir/".$ent->{name}, \$ent) if($ent->{type} == 0);

    my $fullname = "$dir/".$ent->{name};

    my $match = 0;
    if($d_mode){
      if($dhash{$ent->{name}}){
        $match = 1  if $dstent[$dhash{$ent->{name}}]->{name};  #means the destination DOES exist
        $match += 2 if $dstent[$dhash{$ent->{name}}]->{type} eq $ent->{type}; #means the type is the same
        $match += 4 if $dstent[$dhash{$ent->{name}}]->{inode} eq $ent->{inode}; #means it's the same inode
      }
    }

    #directories
    if($ent->{type} == 4){
      fillstats("$src/$dir/".$ent->{name}, \$ent) unless ($ent->{mode});
      if($match == 1){
        print "filetype diff\t$fullname\n" if $DEBUG{PROGRESS};
        deletefile($fullname);
      }  
      #we will allways recursively compare since the source is a directory
      recursivecompare($fullname,$ent->{mode}, $ent->{uid} , $ent->{gid}, $ent->{mtime});
    #files/links/special files
    }else{
      if($match == 7){ 
#        print "match!\n"
      }elsif($match == 3){
        print "inode differ\t$fullname\n" if $DEBUG{PROGRESS};
        deletefile($fullname);
        linkfile($fullname);
      }elsif($match == 1){
        if($dstent[$dhash{$ent->{name}}]->{type} == 4){
          print "filetype dst is dir diff\t$fullname\n" if $DEBUG{PROGRESS};
          recursivedelete("$fullname");
        }else{
          print "filetype dst is non dir diff\t$fullname\n" if $DEBUG{PROGRESS};
          deletefile($fullname);
        }
        linkfile($fullname);
      }elsif($match == 0){
#        print "src f exist\t$fullname\n";
        linkfile($fullname);
       }else{
        print "file - other\t".$ent->{type}." $match $fullname\n" if $DEBUG{PROGRESS};
      }
    }
  }

  #now spin through the destination if it exists and purge things that shouldn't exist
  foreach my $ent (sort { $$a{'inode'} <=> $$b{'inode'}} @dstent){
    next if $seen{$ent->{name}};
    my $fullname = "$dir/".$ent->{name};
    #directories we have to recursively delete
    if($ent->{type} == 4){
      recursivedelete("$fullname");
    #everything else we just unlink
    }else{
      deletefile("$fullname");
    }
  }
}

sub fillstats {
  my $file = shift;
  my $e_ref = shift;
  my @a = lstat($file);
  if($a[2] & S_IFREG){
    $$e_ref->{type} = 8;
  }elsif($a[2] & S_IFCHR){
    $$e_ref->{type} = 2;
  }elsif($a[2] & S_IFDIR){
    $$e_ref->{type} = 4;
  }elsif($a[2] & S_IFLNK){
    $$e_ref->{type} = 10;
  }elsif($a[2] & S_IFBLK){
    $$e_ref->{type} = 6;
  }elsif($a[2] & S_IFSOCK){
    $$e_ref->{type} = 12;
  }elsif($a[2] & S_IFIFO){
    $$e_ref->{type} = 1;
  }elsif($a[2] & S_IFWHT){
    $$e_ref->{type} = 14;
  }else{
    $$e_ref->{type} = 0;
  }
  $$e_ref->{mode} = $a[2];
  $$e_ref->{uid} = $a[4];
  $$e_ref->{gid} = $a[5];
  $$e_ref->{mtime} = $a[9];
}

sub linkfile {
  my $file = shift;
  print "hardlink file $file\n" if $DEBUG{LINK};
  link("$src/$file","$dst/$file") unless $READONLY;
}

sub recursivedelete {
  my $dir = shift;
  print "recursively deleting $dir\n" if $DEBUG{PROGRESS};
  opendir(DIR,"$dst/$dir");
  my @dirent = readdirent(DIR);
  closedir(DIR);
  foreach my $ent (sort { $$a{'inode'} <=> $$b{'inode'}} @dirent){
    next if ($ent->{name} =~ /^\.\.?$/);
    my $fullname = "$dir/".$ent->{name};

    if($ent->{type} == 0){
      $ent->{type} = 4 if( (lstat( "$dst/$dir/".$ent->{name}))[2] & S_IFDIR);
    }
    #directories
    if($ent->{type} == 4){
      recursivedelete($fullname);
    }else{
      deletefile($fullname);
    }
  }
  print "rmdir $dst/$dir\n" if $DEBUG{RMDIR};
  unless($READONLY){
    rmdir("$dst/$dir") or warn("failed to rmdir $dst/$dir $!");
  }
}

sub deletefile {
  my $file = shift;
  print "deleteing $file\n" if $DEBUG{UNLINK};
  unless($READONLY){
    unlink "$dst/$file" or warn("failed to unlink $dst/$file $!");
  }
}
