ldb

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

$cwd = getcwd();
require($cwd.'/vendor/autoload.php');

$cli = new \Tlf\Cli();

$cli->load_json_file($cwd.'/.config/ldb.json');
$cli->load_stdin();

if (!function_exists('readline')){
    function readline($prompt){
        echo "\n\nreadline() not supported. Automatic YES to prompt\n\n";
        echo "\n$prompt\n";
        return 'y';
    }
}


/**
 * Migrate database
 * @arg old_version integer
 * @arg new_version integer
 * @param -db, optional relative path to a file that returns a pdo object
 * @usage vendor/bin/ldb migrate -db db/pdo.php -dir db 0 1
 */
$cli->load_command('migrate', 
    function($cli, $args) use ($cwd){

        if (!isset($args['--'][0])||!isset($args['--'][1])){
            echo "\nVersions to migrate from/to were not passed. Example: `ldb migrate 1 2` would upgrade from v1 to v2. You can go up or down & migrate multiple versions at once";
            return;
        }
        $old_version = (int)$args['--'][0];
        $new_version = (int)$args['--'][1];

        $db = $args['db'] ?? 'db.php';
        $db_file = $cwd.'/'.$db;
        if (!file_exists($db_file)){
            echo "\nDb file $db in $cwd does not exist. Create '$db' or pass `-db rel/path/to/db-file.php` & that file MUST return a pdo object.";
            return;
        }
        $pdo = require($db_file);
        if (!$pdo instanceof \PDO){
            echo "\nDb file '$db' exists but does not return a PDO object.";
            return;
        }


        $dir = $args['dir'] ?? 'db';
        $dir_path = $cwd.'/'.$dir;
        if (!is_dir($dir_path)){
            echo "\nMigration dir '$dir' does not exist in '$cwd'.";
            echo "\nPass `-dir rel/path` or create dir `$dir` with your migrations in it.";
            return;
        }

        echo "\nMigrate from $old_version to $new_version using migrations in '$dir'\n";
        $answer = readline("\nAre you sure? (y/n)");
        if ($answer!=='y'){echo "\nCanceled migration.\n";}
        $lilm = new \Tlf\LilMigrations($pdo,$dir);
        $lilm->migrate($old_version, $new_version);
    },
    "Update your database. pass `-db rel/path/to/pdo.php -dir rel/path/to/migrations/`. -dir is optional. pdo.php MUST return a pdo object"
);


$cli->execute();
echo "\n";