#!/usr/bin/perl

use strict;
use warnings;
use Date::Format;
use Date::Language;
use File::Spec;
use File::Find::Rule;
use Cwd;

my $home="$ENV{HOME}";
my $dirname=".stdacct";
my $datelang = Date::Language->new('English');
my $backupsuff=$datelang->time2str("%Y%m%d%H%M%S", time);
my $dotfileprefix="dotfiles/";

# TODO: remove stale symlinks pointing to $dirname

chdir($home. "/". $dirname);

sub process_single_symlink {
    my ($source, $target) = @_;
    print "symlink ". $source. " ". $target. " ";
    my $action="create";
    if( -l $target ) {
	my $extsource=readlink($target);
	print "exists as link to ". $extsource. " ";
	if( $extsource eq $source ) {
	    print "(ok).";
	    $action="finish";
	} else {
	    $action="rename";
	}
    } elsif( -f $target ) {
	print "is a file ";
        $action="rename";
    } elsif( ! -e $target ) {
	print "does not exist ";
    } else {
	print "is other file type (aborting).";
	$action="finish";
    }
    if( $action eq "rename" ) {
	rename($target, $target. ".stdacct-backup.". $backupsuff);
	print "renaming ";
	$action="create";
    }
    if( $action eq "create" ) {
	my ($volume,$directories,$filename)=File::Spec->splitpath($target);
	if( ! -e $directories ) {
	    print "parent dir does not exist, creating dir, ";
	    mkdir( $directories );
	}
	if( ! -d $directories ) {
	    print "parent $directories is not a directory (aborting)";
	} else {
	    print "creating.";
	    symlink($source, $target) or die "cannot create symlink $target -> $source: $!\n";
	}
    }
    print "\n";
}

sub process_dir {
    my ($file) = @_;
    (my $unprefixed=$file) =~ s/^$dotfileprefix//;
    my ($volume,$directories,$filename)=File::Spec->splitpath($unprefixed);
    
    my $source=File::Spec->canonpath("./". File::Spec->abs2rel($home. "/". $dirname, $home. "/". $dirname. "/". $directories). "/". $dirname. "/". $file);
    my $target=$home. "/". $unprefixed;
    process_single_symlink($source, $target);
}


foreach my $link ( File::Find::Rule->maxdepth(1)->symlink()->in("$home") ) {
    my $source=$home. "/". readlink($link);
    unless( -e $source ) {
	print "$link -> $source does not exist, deleting.\n";
	unlink( $link );
    }
}

foreach my $dir ( File::Find::Rule->file()->in("$dotfileprefix") ) {
    process_dir($dir);
}
	      
my $sshsubdirprefix=File::Spec->canonpath("./". File::Spec->abs2rel($home. "/". $dirname, $home. "/". $dirname. "/ssh/"));
process_single_symlink("$sshsubdirprefix/.stdacct/ssh/config.d", "$home/.ssh/config.d");
process_single_symlink("$sshsubdirprefix/.stdacct/ssh/authorized_keys.d", "$home/.ssh/authorized_keys.d");
