<?php
//
// DB Migration Script
// Copyright (c) 2017 - Nagios Enterprises, LLC. All rights reserved.
//

define('SUBSYSTEM', 1);
require_once('/usr/local/nagiosfusion/html/includes/base.inc.php');

echo "Upgrading database!\n";

$db_version = get_option('db_version');

$to_version = $db_version;

if ($argc < 2) {
    echo "No version specified to upgrade to!\n";
    exit(0);
}
$to_version = intval($argv[1]);

echo " * Upgrading from version: $db_version\n";
echo " *             to version: $to_version\n";

$migration_dir = dirname(__FILE__) . '/migrations/';
if (!is_dir($migration_dir)) {
    echo " * Migration directory: $migration_dir does not exist, bailing!\n";
    exit(0);
}
$tmp_files = scandir($migration_dir);
if (!is_array($tmp_files)) {
    echo " * Scanning migration directory: $migration_dir resulted in error, bailing\n";
    exit(0);
}
$migration_files = array();
echo " * Migration files:\n";
foreach($tmp_files as $migration_file) {
    if ($migration_file == '.' || $migration_file == '..') {
        continue;
    }
    $migration_files[] = $migration_file;
    echo "   - {$migration_file}\n";
}
if (count($migration_files) <= 0) {
    echo " * No migration files found\n";
    exit(0);
}

global $cfg;

if (!isset($cfg['database']['fusion']) || !is_array($cfg['database']['fusion'])) {
    echo " * UNRECOVERABLE ERROR GRABBING CFG DATA, bailing\n";
    exit(0);
}

$dbarr = $cfg['database']['fusion'];

$user = grab_array_var($dbarr, 'user', 'fusion');
$pass = grab_array_var($dbarr, 'pass', 'fusion');
$host = grab_array_var($dbarr, 'host', 'localhost');
$port = intval(grab_array_var($dbarr, 'port', 3306));
$dbname = grab_array_var($dbarr, 'dbname', 'fusion');

$highest_version = $to_version;

foreach ($migration_files as $file) {

    if ($file == '.' || $file == '..')
        continue;
    if (strpos($file, '.sql') === false)
        continue;

    echo " * Checking $file\n";

    $file_version = basename($file, ".sql");

    if ($file_version <= $db_version) {
        echo " ** Is less than previous version, skipping\n";
        continue;
    }

    $cmd = "mysql -u {$user} -h \"$host\" ";
    if ($port != 3306 && !empty($port))
        $cmd .= "--port=$port ";

    $cmd .= "--password=\"$pass\" $dbname < {$migration_dir}{$file}";

    echo " * Executing: $cmd\n";

    $output = array();
    $ret = 0;
    exec($cmd, $output, $ret);
    foreach($output as $output_line) {
        echo " * * $output_line\n";
    }
    if ($ret != 0) {
        echo "Failed running command!\n";
        continue;
    }

    // don't incremenet this on failure
    if ($file_version > $highest_version)
        $highest_version = $file_version;
}


echo " * Updating db_version to $highest_version\n";
set_option('db_version', $highest_version);
