<?php
    /**
     * Run logger script.
     *
     * Exposes an API to save a run to the database.
     * Reads post data and calls the log-run.py script.
     * Mandatory POST parameters are:
     *  - data: Received JSON file after a run.
     *  - key: User API key.
     *
     * @category API
     */

    namespace swdb;

    $status = 200;
    if (isset($_POST["data"]) && isset($_POST["key"])){
        $data = $_POST["data"];
        $key = $_POST["key"];
        if (json_decode($data) === null){
            error_log("ERROR: API v1 log-run: Invalid JSON");
            $status = 400;
        }
        else{
            $cmd = $_SERVER["DOCUMENT_ROOT"] . "/../application/bin/log-run.py " . $key . " " . escapeshellarg($data);
            $out = [];
            $ret = 0;
            exec($cmd, $out, $ret);
            if ($ret != 0){
                error_log("ERROR: API v1 log-run exited with status: " . $ret);
                error_log("====================");
                error_log("|| SCRIPT OUTPUT: ||");
                error_log("===============================================================================");
                foreach($out as $line){
                    error_log("|| " . $line);
                }
                error_log("===============================================================================");
                $status = 400;
            }
        }
    }
    else{
        error_log("ERROR: API v1 log-run: Invalid JSON");
        $status = 400;
    }
    http_response_code($status);
    return $status;
?>

