<?php
/*
 * Copyright (c) 2003-2022 Willem Dijkstra
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *    - Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *    - Redistributions in binary form must reproduce the above
 *      copyright notice, this list of conditions and the following
 *      disclaimer in the documentation and/or other materials provided
 *      with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 */

require_once(__DIR__ . "/setup.inc");
require_once(__DIR__ . "/class_vars.inc");

function hash2cmdline(&$args) {
    reset($args);
    $cmdline = '';

    foreach($args as $key => $value) {
        $cmdline .= " ".escapeshellarg((string) $value);
    }

    return $cmdline;
}

function get_extension($filename) {
    preg_match("/\.([^\.]+)$/", (string) $filename, $match);
    if (isset($match[1])) {
        return $match[1];
    } else {
        return '';
    }
}

function normalise_filename($filename) {
    /* remove basename and trailing extension from filename */
    $filename = basename((string) $filename);
    if (preg_match("/^([^\.]+)/", $filename, $match)) {
        $filename = $match[1];
    }
    /* remove all but lowercase, digits and minus */
    $filename = preg_replace("/[^a-z0-9_-]/", '', $filename);

    return $filename;
}

function parse_filename($name, $filename, $index='') {
    /*
     * cut up the filename matching to several statements; the current
     * filename forms are so diverse that one regexp is possible, but hard
     * to maintain
     */
    global $symon;

    $r = new Vars();

    if (preg_match("/^(.*\/)?(mem|pf|pfs|debug|mbuf).rrd$/",
                   (string) $filename, $match)) {
        /* simple form; rrdtype only */
        $r->def('rrdtype'. $index, $match[2]);
        $r->def('title'. $index,
                $match[2] . ' of ' . $name);
    } elseif (preg_match("/^(.*\\/)?(cpu|cpuiow)(\\d{0,2}).rrd\$/",
                         (string) $filename, $match)) {
        /* <name><number>.rrd */
        $r->def('rrdtype'. $index, $match[2]);
        $r->def('title'. $index,
                $match[2].'('.$match[3].') of '. $name);
    } elseif (preg_match("/^(.*\/)?(if|pfq|proc)_([A-Za-z\.-]+)([\.0-9]{0,4}).rrd$/",
                         (string) $filename, $match)) {
        /* <name>_<identifier><number>.rrd */
        $r->def('rrdtype'. $index, $match[2]);
        $r->def('rrdwhat'. $index, $match[3]);
        $r->def('rrdwhich'. $index, $match[4]);
        $r->def('title'. $index,
                $match[2].'('.$match[3].$match[4].') of '. $name);
    } elseif (preg_match("/^(.*\/)?(pfq)_([a-z0-9\.-]+)_([a-z0-9_\.-]+).rrd$/",
                         (string) $filename, $match)) {
        /* pfq_<identifier1>_<identifier2>.rrd */
        $r->def('rrdtype'. $index, $match[2]);
        $r->def('rrdwhat'. $index, $match[3]);
        $r->def('rrdwhich'. $index, $match[4]);
        $r->def('title'. $index,
                $match[2].'('.$match[3].'/'.$match[4].') of '. $name);
    } elseif (preg_match("/^(.*\\/)?(io|iops|df)(\\d{0,2})_([A-Za-z0-9_\\.-]+).rrd\$/",
                         (string) $filename, $match)) {
        /* <diskstream><version>_<identifier>.rrd */
        $r->def('rrdtype'. $index, $match[2].$match[3]);
        if ($symon['options']['driveserial'] &&
            (preg_match("/[_-]([A-Za-z0-9]{8,})$/", $match[4], $submatch))) {
            $match[4] = $submatch[1];
        }
        $r->def('rrdwhat'. $index, $match[4]);
        $r->def('title'. $index,
                $match[2].'('.$match[4].') of '. $name);
    } elseif (preg_match("/^(.*\\/)?(sensor)_([a-z]+\\d{1,2}).([a-z]+\\d{1,2}).rrd\$/",
                         (string) $filename, $match)) {
        /* sensor_<name>.<name>.rrd */
        $r->def('rrdtype'. $index, $match[2]);
        $r->def('rrdwhat'. $index, $match[3]);
        $r->def('rrdwhich'. $index, $match[4]);
        $r->def('title'. $index,
                $match[2].'('.$match[3].'.'.$match[4].') of '. $name);
    } elseif (preg_match("/^(.*\\/)?(load)(\\d{0,2}).rrd\$/",
                         (string) $filename, $match)) {
        /* load_<name>.<name>.rrd */
        $r->def('rrdtype'. $index, $match[2]);
        $r->def('title'. $index,
                $match[2].' of '. $name);
    } elseif (preg_match("/^(.*\/)?(smart)_([a-zA-Z][A-Za-z0-9_-]+).rrd$/",
                         (string) $filename, $match)) {
        /* smart_<name>.rrd */
        $r->def('rrdtype'. $index, $match[2]);
        if ($symon['options']['driveserial'] &&
            (preg_match("/[_-]([A-Za-z0-9]{8,})$/", $match[3], $submatch))) {
            $match[3] = $submatch[1];
        }
        $r->def('rrdwhat'. $index, $match[3]);
        $r->def('title'. $index,
                $match[2].'('.$match[3].') of '. $name);
    } elseif (preg_match("/^(.*\/)?(flukso)_([0-9a-f]{32}).rrd$/",
                         (string) $filename, $match)) {
        /* sensor_<name>.<name>.rrd */
        $r->def('rrdtype'. $index, $match[2]);
        $r->def('rrdwhat'. $index, $match[3]);
        $r->def('title'. $index,
                $match[2].'('.$match[3].') of '. $name);
    } else {
        warning('cannot determine rrd type from filename "'.$filename.'"');
    }

    return $r;
}

function save($filename, &$data) {
    $fh = fopen($filename, 'w');

    if (!$fh) {
        runtime_error('tools: cannot open file "'.$filename.'" for writing');
        return 0;
    }

    $mydata = is_array($data) ? implode("\xa", $data) : $data;

    $result = fwrite($fh, (string) $mydata);

    fflush($fh);
    fclose($fh);

    return $result;
}

function load($filename) {
    global $symon;

    $fh = fopen($filename, 'r');

    if (!$fh) {
        runtime_error('tools: cannot open file "'.$filename.'" for reading');
        return 0;
    }

    $data = fread($fh, $symon['loadbuffer']);

    fclose($fh);

    return $data;
}

function config_error($item, $problem): never {
    global $symon;
    print("\xa\xa".'<b>check setup.inc: $symon["'.$item.'"]="'.
          $symon[$item].'" '.$problem);
    exit(1);
}

function runtime_error($problem): never {
    print("\xa\xa<b>".$problem.'</b>');
    error_log($problem);
    exit(1);
}

function warning($problem) {
    print("\xa\xa<b>".$problem.'</b>');
    error_log($problem);
}

/* Polyfill for PHP 4 - PHP 7 */
if (!function_exists('str_contains')) {
    function str_contains (string $haystack, string $needle) {
        return empty($needle) || strpos($haystack, $needle) !== false;
    }
}
?>
