#!/usr/bin/perl -w

use File::Path;

my $db = "/var/lib/dpkg/info";
my $vim = "$ENV{HOME}/.vim";

sub install_script {
	# is there a parameter to take care of?
	if (!($_[0])) 
		{ die "Please specify the name of script to install.\n" };
	
	# is there ~/.vim?
	mkdir $vim;
	if ($! and ! -d $vim) 
		{ die "Something is wrong with your ~/.vim/ directory:\n$!\n" };
	
	# get the list of files and link them
	open(F,$db . "/vim-" . $_[0] . ".list") 
		or die "Script $_[0] has not been found.\nPerhaps it has not been installed site-wide from .deb package?\n";

	while (<F>) {
		chomp;
		if (m#^/usr/share/vim/addons/#) {
			($lf = $_)  =~ s#^/usr/share/vim/addons/##; $lf = "$vim/$lf";
			($ld = $lf) =~ s#/[^/]*?$##; 
			
			mkpath $ld;
			if ($! and ! -d $ld)
				{ die "Something is wrong with your $ld directory:\n$!\n" };
			
			symlink $_, $lf;
			if ($! and ! -l $lf)
				{ die "Something is wrong with your $lf symlink:\n$!\n" };

			if (readlink $lf ne $_)
				{ unlink $lf; symlink $_, $lf };

			print "$_ linked OK.\n";
		}
	}
	close(F);
	print "Script $_[0] has been installed.\n";
}

sub remove_script {
	# is there a parameter to take care of?
	if (!($_[0])) 
		{ die "Please specify the name of script to remove.\n" };
	
	# get the list of files and link them
	open(F,$db . "/vim-" . $_[0] . ".list") 
		or die "Script $_[0] has not been found.\nPerhaps it has not been installed site-wide from .deb package?\n";

	my $count=0;
	while (<F>) {
		chomp;
		if (m#^/usr/share/vim/addons/#) {
			($lf = $_)  =~ s#^/usr/share/vim/addons/##; $lf = "$vim/$lf";
			($ld = $lf) =~ s#/[^/]*?$##; 
			
			if (-l $lf)	{ 
				$!=0;
				unlink $lf;
				if ($!)	{ die "Something went wrong while removing $lf link:\n$!\n" };
				$count++;
				$dirs{$ld}++;
				print "$lf link removed OK.\n";
			}
			else {
				print "WARNING: $lf is NOT a symlink, please check it!\n";
			};
		}
	}
	close(F);
	if ($count) {
		print "Script $_[0] has been removed. $count links removed.\n";
		if (%dirs) { 
			print "Please check following dirs, they may have been emptied:\n", join "\n", sort(keys %dirs), "\n" };
	}
	else {
		print "Script $_[0] has NOT been removed.\nEither $_[0] wasn't installed in ~/.vim or you have messed something up...\n";
	};
}

for ($ARGV[0] || "help") {
        if (/^install$/)	{ install_script($ARGV[1]) }
        elsif (/^remove$/)	{ remove_script($ARGV[1])  }
        else				{ print 
"A script to manage ~/.vim -> /usr/share/vim/addons links.
usage: 
$0 command [options] where available commands are:
\tinstall foo\tcreates links from ~/.vim/ to /usr/share/vim/addons for script foo
\tremove foo\tremoves links from ~/.vim/ to /usr/share/vim/addons for script foo
\thelp\t\tget this help message
"; }
}

