#! /usr/bin/env php
<?php

// Job submission and control script for TreeThreader application
// from the Institute for Computing Technology in Beijing
//

define("PROJECT", "http://casathome.ihep.ac.cn/");

function usage() {
    global $argv;
    die("
Usage:
$argv[0] submit sequence_file	(submit batch, print batch ID)
$argv[0] get_output batch_id 	(show URL of output file)
\n");
}

function get_auth() {
    return trim(file_get_contents("auth"));
}

function do_http_op($xml, $file=null) {
    $ch = curl_init(PROJECT."tree_threader.php");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if ($file) {
        $fields = array('request' => $xml, 'seq_file' => "@$file");
    } else {
        $fields = "request=$xml";
    }
    if (!curl_setopt($ch, CURLOPT_POSTFIELDS, $fields)) {
        die("curl_setopt failed\n");
    }
    $reply = curl_exec($ch);
    if (!$reply) return array(null, "HTTP error");
    $r = simplexml_load_string($reply);
    if (!$r) return array(null, "Can't parse reply XML: <pre>".htmlentities($reply)."</pre>");
    return array($r, null);
}

function handle_submit() {
    global $argc, $argv;
    if ($argc != 3) usage();
    if (!is_file($argv[2])) die("seq file missing");
    $auth = get_auth();
    $req_xml = "
<tt_request>
    <action>submit</action>
    <auth>$auth</auth>
</tt_request>
";
    list($reply, $errmsg) = do_http_op($req_xml, $argv[2]);
    if ($errmsg) die("Error: $errmsg\n");
print_r($reply);
    echo "batch ID: ".(int)$reply->batch_id."\n";
}

function handle_get_output() {
    global $argc, $argv;
    if ($argc != 3) usage();
    $batch_id = $argv[2];
    //$auth = $argv[3];
    $auth = get_auth();
    $req_xml = "
<tt_request>
    <action>get_output</action>
    <batch_id>$batch_id</batch_id>
    <auth>$auth</auth>
</tt_request>
";
    list($reply, $errmsg) = do_http_op($req_xml);
    if ($errmsg) die("Error: $errmsg\n");
    echo (string)$reply->url, "\n";
}

if ($argc < 2) usage();
switch ($argv[1]) {
case "submit": handle_submit(); break;
case "get_output": handle_get_output(); break;
default: usage();
}

?>
