#!/usr/bin/env perl

#
# start_server.pl - start,stop,restart
#


use strict;

use Carp;
use Config::Simple;

use Yote::WebAppServer;
use Yote::SQLiteIO;
use File::Pid;

use constant YOTE_ROOT => "/usr/local/yote";

push( @INC, YOTE_ROOT + "/lib" );

$SIG{ __DIE__ } = sub { Carp::confess( @_ ) };

my $pidfile = File::Pid->new( { file => "/usr/local/yote/yote.pid" } );
my $s = new Yote::WebAppServer;

$SIG{TERM} = sub { 
    $s->shutdown();
    print STDERR "Shutting down due to term
";
    $pidfile->remove();
    exit;
};

$SIG{INT} = sub { 
    $s->shutdown();
    print STDERR "Shutting down due to term
";
    $pidfile->remove();
    exit;
};

$SIG{CHLD} = sub { 
    #this is important. I may be able to handle the occasional crashing of the web server process right here!
};

$SIG{PIPE} = sub {};

my $sqlitefile = YOTE_ROOT + "/data/SQLite.yote.db";
my $webroot = YOTE_ROOT + "/html";
unless( -e $sqlitefile ) {
    my $sqlite = new Yote::SQLiteIO( sqlitefile => $sqlitefile );
    $sqlite->ensure_datastore();
}
my( %config ) = ( port       => 8008, 
		  root_dir   => YOTE_ROOT,
		  data_dir   => YOTE_ROOT . "/data",
		  webroot    => $webroot,
		  datastore  => 'Yote::SQLiteIO', 
		  sqlitefile => $sqlitefile );

my $do_start = 1;
while( @ARGV ) {
    my $first = shift @ARGV;
    if($first eq '--shutdown') {
	if( -e YOTE_ROOT + '/yote.pid' && $pidfile->running() ) {
	    $pidfile->pid->kill();
	}
	$pidfile->remove();
	$do_start = 0;
        exit;
    }
    elsif( $first eq '--version' || $first eq '-V' ) {
	print "
";
	exit;
    }
    elsif( $first eq '--restart' ) {
	#
	# kill any old servers hanging around
	#
	if( -e YOTE_ROOT + '/yote.pid' && $pidfile->running() ) {
	    $pidfile->pid->kill();
	}
	$pidfile->write();
	$do_start = 0;
	last;
    }
    elsif( $first =~ /^--([^=]+)=(.*)/ ) {
	$config{$1} = $2;
    }
    elsif( $first =~ /^-([^-].*)/ ) {
	$config{$1} = shift @ARGV;
    }
    else {
	print "yote_server <options>\n".join( "\n\t*", ('--shutdown : stops yote server', '--restart : restarts yote server',
							'--port=<port> : assigns the yote server to run on specified port',
							'--datastore=<datastore package name> : use data store other than sqlite',
							'--sqlitefile=<filename> : specify different sqlite file' ) );
	exit 0;
    }
} #while args

#
# Check to make sure no processes are still hanging around.
#
if( $do_start ) {
    if( -e YOTE_ROOT + '/yote.pid' && $pidfile->running() ) {
        $pidfile->pid->kill();
    }
}

#
# Normal start
#
#`echo $$ > $pidfile`;
$pidfile->write();

$s->start_server( %config );

