#!/usr/bin/perl

use strict;
use warnings "all";
use JSON::PP;

sub help;
sub ctrl ($);
sub status;

my $sep = $/;
$/ = '';

open (CONF, "$ENV{HOME}/.local/etc/svc.json") or die "No config at $ENV{HOME}/.local/etc/svc.json\n";

my $c = <CONF>;
close CONF;
$/ = $sep;

$c = decode_json($c);

if ($c->{mode} eq 'user') {
	die "\$HOME is no set\n" unless (defined($ENV{HOME}));
	die "$ENV{HOME} does not exist" unless (-d $ENV{HOME});
	chdir $ENV{HOME};
	die "No such directory $ENV{HOME}$c->{dir}\n" unless(-d "$ENV{HOME}$c->{dir}");
	chdir "$ENV{HOME}$c->{dir}";
} else {
	die "No such directory $c->{dir}" unless(-d $c->{dir});
	chdir $c->{dir};
}

help unless (defined($ARGV[0]) || defined($ARGV[1]));

if ((-l "./$ARGV[0]") || (-d "./$ARGV[0]")) {
	chdir "./$ARGV[0]";
	die "Is service running?\n" unless (-d './supervise');
	chdir './supervise';

	if ($ARGV[1] eq 'start') {
		die "Service $ARGV[0] already running.\n" if (status() eq 'run');
		ctrl('u');
	} elsif ($ARGV[1] eq 'restart') {
		die "Service $ARGV[0] already stopped.\n" if (status() eq 'down');
		ctrl('d');

		for (my $cnt = 0; $cnt < $c->{timeout}; $cnt++) {
			if (status() eq 'down') {
				last;
			}

			sleep 1;
		}

		ctrl('k') if (status() ne 'down');
		sleep 1;
		ctrl('u');
	} elsif ($ARGV[1] eq 'stop') {
		die "Service $ARGV[0] already stopped.\n" if (status() eq 'down');
		ctrl('d');

		for (my $cnt = 0; $cnt < $c->{timeout}; $cnt++) {
			if (status() eq 'down') {
				last;
			}

			sleep 1;
		}

		ctrl('k') if (status() ne 'down');
		sleep 1;
	} elsif ($ARGV[1] eq 'status') {
		print status() . "\n";
	}
} else {
	die "No such service.\n";
}

exit 0;

sub help {
	print "Usage $0 SERVICE [start|stop|restart|status]\n";
	exit 0;
}

sub ctrl ($) {
	my $command = shift;
	open (C, ">", "control") or die;
	print C $command;
	close C;
}

sub status {
	open (S, "stat") or die;
	my $status = <S>;
	chomp($status);
	close S;
	return $status;
}

# vim: set ft=perl noet ai :
