#!/usr/bin/perl
use strict;
my($app_svnid) = '$HeadURL$ $LastChangedRevision$';
#  Allow bare words, so &ade_err_error() calls look nicer.
no strict 'subs';
use lib substr `ade-config ade_include_prefix`,0,-1;
use ADE;
use lib substr `js-config js_include_prefix`,0,-1;
use experimental 'smartmatch';

my(%jsc_defined_errors) = (
    jsc_err_misc         => { fmt => "%s" },
);

#  Options
my(%opt_resources);
my($opt_lock_file);

#  Other globals

sub jsc
{
    my($errstack_ref) = @_;
    my($rc, @select_results, $job_id, $dbh, $command, $i, $sql_statement, $resource);
    my(@local_errstack);
    my($db_file, $jsd_pid, $running_flag);

    #  Set ADE options
    &ade_err_registerdefderrs(\%jsc_defined_errors);
    &ade_err_resetstack($errstack_ref, dumpall=>0);

    #  Defaults for options 
    #  (identical line in jsd, jsc, jsq).
    $opt_lock_file = $ENV{JSD_LOCKFILE} ? $ENV{JSD_LOCKFILE} : "$ade_tmp_dir/jsd-$ENV{'LOGNAME'}.lock";

    #  Register options
    if (($rc=&ade_opt_register($errstack_ref, "l:s", "lockfile:s", "main::jsc_opt_handler_%s")) != $ade_err_ok) {
        return($rc);
    }

    #  Register handler functions
    if (($rc=&ade_msg_register($errstack_ref, \&jsc_usage, \&jsc_version, \&jsc_listpaths)) != $ade_err_ok) {
        return($rc);
    } 

    #  Process options
    if (($rc=&ade_opt_process($errstack_ref)) != $ade_err_ok) {
        return($rc);
    } 
    
    #  Process arguments
    &ade_msg_usage($errstack_ref, \&app_usage, 1) if ($#ARGV+1 == 0);
    $command = $ARGV[0];
    shift @ARGV;
    &ade_err_debug($errstack_ref, 10, "jsc: \$command=\"$command\", ARGV=" . join(',', @ARGV));

    #  Sanity checks and derivation
    if (($rc=&ade_lck_checklock($errstack_ref, $opt_lock_file, \$jsd_pid, \$running_flag)) != $ade_err_ok) {
        &ade_err_debug($errstack_ref, 20, "ade_lck_lock: ade_lck_checklock failed");
        return($rc);
    }
    if (!$running_flag) {
        &ade_err_error($errstack_ref, jsc_err_misc, "jsd: not running");
        return($ade_err_fail);
    }
    #  Predicable path to database. Tests should not normally need to access the database.
    $db_file = "/var/tmp/jsd-$jsd_pid.sqlite";

    #  Initialise database
    if (! -w $db_file) {
        &ade_err_error($errstack_ref, jsc_err_misc, "$db_file: not accessible");
        return($ade_err_fail);
    }
    my %attr = ( RaiseError => 1, HandleError => sub { return 1; } );
    if (!defined($dbh = DBI->connect("dbi:SQLite:dbname=$db_file","","", \%attr))) {
        &ade_err_error($errstack_ref, jsc_err_misc, $DBI::errstr);
        return($ade_err_fail);
    }

    #  Enforce foreign key constraints
    $sql_statement = "PRAGMA foreign_keys=ON;";
    if (($rc=&ade_sql_execute($errstack_ref, $dbh, $sql_statement)) != $ade_err_ok) {
        return($rc);
    }
    #  Set 10s timeout
    $dbh->sqlite_busy_timeout(10000);

    #  Guts
    &ade_err_debug($errstack_ref, 10, "jsc: inserting ...");
    $sql_statement = "INSERT INTO commands (command) VALUES ('$command');";
    if (($rc=&ade_sql_execute($errstack_ref, $dbh, $sql_statement)) != $ade_err_ok) {
        return($rc);
    }
    
    #  Tell daemon something is in command queue.
    &ade_err_debug($errstack_ref, 10, "jsc: waking jsd ...");
    if (kill(USR1,$jsd_pid) != 1) {
        &ade_err_error($errstack_ref, jsc_err_misc, "failed to nudge process $jsd_pid");
        return($ade_err_fail);
    }

    #  Tidy up
    $dbh->disconnect;

    return ($ade_err_ok);
}

sub jsc_opt_handler_l
{
    my($errstack_ref,$lock_file) = @_;

    $opt_lock_file = $lock_file;

    return $ade_err_ok;
}

sub jsc_opt_handler_lockfile
{
    return(&jsc_opt_handler_l(@_));
}

sub jsc_version
{
    my($errstack_ref, $version_text_ref) = @_;

    return(&ade_smf_extractversionfromsvnstring($errstack_ref, $app_svnid, $version_text_ref));
}

sub jsc_listpaths
{
    my($errstack_ref, $pathlist_text_ref) = @_;
    my($rc);

    ${$pathlist_text_ref} = "Lock-File: $opt_lock_file\n";

    return($ade_err_ok);
}

sub jsc_usage
{
    my($errstack_ref, $usage_text_ref, $passno) = @_;

    if ($passno == 1) {
        ${$usage_text_ref} = "\n";
    } elsif ($passno == 2) {
        ${$usage_text_ref} = "         -l <file> | --lockfile=<file>       set lock file\n";
    }

    return($ade_err_ok);
}

&ade_gep_main(\&jsc);
