#!/usr/bin/perl
use strict;
use warnings;

use Cwd;

sub help {
    if(my $cmd = shift) {
	die "command $cmd needs module\n";
    }
    die "usage: gjservice list\n" .
	"  toggle <module>\n";
}

my $command = shift;
help unless $command;

my $serverdir = ($< ? "$ENV{HOME}/GranJefe" : '/var/GranJefe') . '/plib';

if($command eq 'list') {
    chdir $serverdir;
    my @installed =
	(map { s/.gjm$//; "$_\tON\n" } glob '*.gjm'),
	map { s/.gjm.off//; "$_\tOFF\n" } glob '*.gjm.off';
    warn @installed ? @installed : "No modules installed\n";
    exit(0);
}

my $module = shift;
help($command) unless $module;
my $oname;

if(-d $module) {
    chdir $module;
    $module = 'this';
}

if($module eq 'this') {
    die "Not in a module directory!\n" unless -d 'plib';
    ($module) = reverse glob '*.gj[mp]';
    $oname = $module;
    die "Module file not found!\n" unless $module;
    $module =~ s/.gj[pm]$//;
}

my @states = ("$serverdir/$module.gjm", "$serverdir/$module.gjm.off");
if($command eq 'install') {
    my($found) = grep { -l } @states;
    if($found) {
	warn sprintf("$module already installed, is %s.\n", $found =~ /\.off$/ ? 'OFF' : 'ON');
	exit 0;
    }
    my $dir = getcwd;
    symlink "$dir/$oname" => $states[0]
	or die "Can't create symlink: $!\n";
    warn "Installed as $states[0]\n";
    exit 0;
}

if($command eq 'remove') {
    my($found) = grep { -l } @states;
    if($found) {
	unlink $found or die "Can't unlink $found: $!\n";
	warn "$module removed.\n";
	exit 0;
    }
    warn "$module not installed.\n";
}

if($command eq 'toggle') {
    my($found) = grep { -l } @states;
    if($found) {
	(sub { rename $_[0], $_[1] })->(@states[$found =~ /\.off$/ ? (1, 0) : (0, 1)])
	    or die "Can't toggle: $!\n";
	warn sprintf("$module now %s.\n", $found =~ /\.off$/ ? 'ON' : 'OFF');
    } else {
	warn "$module not installed.\n";
    }
    exit 0;
}

warn "Unknown command '$command'\n";
exit 1;
