#!/usr/bin/perl -w

use strict;

my $nrworkspaces=12;

my $home=$ENV{'HOME'};
defined $home && -d $home
	or die "Invalid home directory.\n";

my $display = $ENV{'DISPLAY'};
defined $display or $display = ":0.0";
$display = quote($display);

-d "$home/.rpws" 
	or mkdir "$home/.rpws", 0700
	or die "Unable to create directory `$home/.rpws` ($!)\n";

-d "$home/.rpws/$display"
	or mkdir "$home/.rpws/$display", 0700
	or die "Unable to create directory `$home/.rpws/$display` ($!)\n";

@ARGV !=0 or die "Usage: $0 (init|save|restore) ...\n";

for ($ARGV[0]) {
	/^init$/ && do {
		for (my $i=1; $i<=$nrworkspaces; $i++) {
			system("ratpoison -c fdump > \Q$home\E/.rpws/$display/$i");
			system "ratpoison", "-c", "bind F$i exec $0 restore $i";
			system "ratpoison", "-c", "bind M-F$i exec $0 save $i";
		}
		last;
	};
	/^restore$/ && do {
		@ARGV == 2 or die "$0 save needs one argument\n";
		my $ws = `cat \Q$home\E/.rpws/$display/\Q$ARGV[1]\E`;
		chomp($ws);
		system "ratpoison", "-c", "frestore " . $ws;
		system "ratpoison", "-c", "echo Workspace $ARGV[1]";
		last;
	};
	/^save$/ && do {
		@ARGV == 2 or die "$0 restore needs one argument\n";
			system("ratpoison -c fdump > \Q$home\E/.rpws/$display/\Q$ARGV[1]\E");
		system "ratpoison", "-c", "echo saved Workspace $ARGV[1]";
		last;
	};
	die "Usage: $0 (init|save|restore)\n";
}

exit 0;

sub quote
{
	my ($name) = @_;

	$name =~ s/([^-a-zA-Z0-9:])/"_" . ord ($1) . "_" /eg;
	return $name;
}


