#!/usr/bin/perl

# Written by Jessica Hamrick, (C) 2010

use strict;
use warnings;
use Getopt::Long;

my $usage = <<USAGE;
Usage: gutenbach-client-config [-l|--list|-a|--add|-d|--delete] [QUEUE] [--host=HOST]

	-l, --list		List available queues
	-a, --add QUEUE		Add a queue (must be used with -h)
	-d, --delete QUEUE	Delete a queue
        -s, --set-default QUEUE Set the default queue
	-h, --host HOST		Hostname for the queue
USAGE

my $list = 0;
my $add = "";
my $delete = "";
my $host = "";
my $default = "";

GetOptions ('l|list' => \$list,
	    's|set-default=s' => \$default,
            'a|add=s' => \$add,
            'd|delete=s' => \$delete,
	    'h|host=s' => \$host);

my $configpath = "$ENV{'HOME'}/.gutenbach";

if (! -e $configpath) {
    mkdir "$configpath";
}
#set given queue to default
if($default and !$add and !$delete and !$list) {
    unless(-e "$configpath/$default") {
	print "Error: queue '$default' doesn't exist yet...you should add it first.\n";
	exit 1;
    }
    if( -e "$configpath/DEFAULT"){
	unlink("$configpath/DEFAULT") or die "Couldn't remove config file '$configpath/DEFAULT'";
    }
    my $symlink_exists = eval { symlink("",""); 1 };
    if ($symlink_exists){
	symlink("$configpath/$default","$configpath/DEFAULT");
	print "Changed default queue to $default.\n";
    }
    else
    {
	print "Error creating symlink to $configpath/$default";
	exit 1;
    }
}
    
	

# list the existing queues
elsif ($list and !$add and !$delete and !$default) {
    my @queues = glob("$configpath/*") or die "Couldn't find configuration files at '$configpath'";

    print "Queue\t\tHost\n";
    foreach my $q (@queues) {
	my ($host, $queue);

	if (-r $q) {
	    local $/;
	    my $fh;
	    open $fh, $q;
	    eval <$fh>;
	}

	print "$queue\t\t$host\n";
    }
}

# add a new queue
elsif (!$list and $add and !$delete) {
    if (!$host) {
	print $usage;
	exit 1;
    }

    if (-e "$configpath/$add") {
	print "Warning: queue '$add' already exists\n";
    }

    open CONFIG, "> $configpath/$add" or die "Couldn't open config file '$configpath/$add'";
    print CONFIG "\$host = \"$host\";\n";
    print CONFIG "\$queue = \"$add\";\n";
    close CONFIG;

    print "Added queue '$add' on host '$host'\n"
}

# delete an existing queue
elsif (!$list and !$add and $delete) {
    if (! -e "$configpath/$delete") {
	print "Error: queue '$delete' already exists\n";
	exit 1;
    }

    unlink("$configpath/$delete") or die "Couldn't remove config file '$configpath/$delete'";
}

else {
    print $usage;
    exit 1;
}
