#! /usr/bin/env php

<?php

// submit a job for existing application
//
// usage: demo_submit appname [infile ...]
//
// Submit a job and show its name.
// Use demo_query to query its status and see output files.
//
// This assumes:
// - template files are appname_in and appname_out
// - the app uses sample_trivial_validator
// - the app uses sample_assimilator
//   (which puts output files in sample_results/)

if ($argc < 2) die("usage: demo_submit appname [infile ...]\n");

$appname = $argv[1];

chdir("html/ops");
require_once("../inc/boinc_db.inc");
chdir("../..");

$app = BoincApp::lookup("name='$appname'");

if (!$app) {
    die("no such application: $appname\n");
}

// load the input template for this app,
// and make sure the right number of input files was specified
//
$path = sprintf('templates/%s_in', $appname);
if (!is_file($path)) {
    die("missing input template $path\n");
}
$intemp = simplexml_load_file($path);
if (!$intemp) die("can't parse input template\n");
$frefs = $intemp->workunit->file_ref;
$nrefs = $frefs->count();

if ($argc-2 != $nrefs) {
    die("wrong number of input files; expected $nrefs\n");
}

// stage the input files
//
$file_list = [];
for ($i=2; $i<$argc; $i++){
    $fname = $argv[2];
    if (!is_file($fname)) {
        die("no such file: $fname\n");
    }
    system("cp $fname `bin/dir_hier_path $fname`", $ret);
    if ($ret) {
        die("Couldn't stage file\n");
    }
    $file_list[] = $fname;
}

// create the job
//
$wu_name = sprintf('%s_%d', $appname, time());
$cmd = sprintf('bin/create_work --appname %s --wu_name %s %s',
    $appname, $wu_name, implode(' ', $file_list)
);
system($cmd, $ret);
if ($ret) {
    die("Couldn't create job\n");
}

echo "Job name: $wu_name\n";

?>
