lia

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

$own_autoload = __DIR__.'/../vendor/autoload.php';
$from_bin_dir_autoload = dirname(__DIR__,3).'/autoload.php';
if (file_exists($from_bin_dir_autoload))require($from_bin_dir_autoload);
else require($own_autoload);

// \Tlf\Server::$IS_TLFSERV_CLI = true;

// $cli->load_inputs(json_decode(file_get_contents(__DIR__.'/defaults.json'),true));

if (!class_exists('Tlf\\Cli')){
    echo "\nPlease run `composer install taeluf/cli v0.1` to use cli commands\n";
    exit;
}

$cli = new \Tlf\Cli();
$cli->load_stdin();


$cli->load_command('main',
    function($cli,$args){
        $cli->call_command('help');
    }, 'alias for help'
);

/**
 * Run all the other commands 
 */
$cli->load_command('all',
    function($cli, $args){
        echo "\n\nRunning all commands\n";
        $cli->call_command('error-page');
        // $cli->call_command('generate-sitemap');
        // $cli->call_command('recompile-phad');
        $cli->call_command('init-analytics');


        echo "\n\nDone running all commands.\n\n";
    }, "Run all the commands"
);

/**
 * Generate an error page.
 *
 * There must be a file `.phptest-host` in the current working directory with a port number. 
 * The site must be running at http://localhost:PORT
 * There must be a route for `/generic-error-page/`
 *
 * Error page is written to `cache/generic-error-page.html`
 *
 */
$cli->load_command('error-page',
    function($cli, $args){
        $_SERVER['REQUEST_URI'] = '/generic-error-page/';
        $_SERVER['HTTP_HOST'] = null;
        $_SERVER['REQUEST_METHOD'] = 'GET';

        $dir = getcwd();
        if (!is_file($dir.'/deliver.php'))$dir = $dir.'/test/Server/';

        $port = file_get_contents($dir.'/.phptest-host');
        $site = 'http://localhost:'.$port;


        $page = file_get_contents($site.'/generic-error-page/');
        $reg = '/\<link rel="stylesheet" href="\/(lia\-resource\.[a-z0-9]+\.min\.css)" \/\>/';
        preg_match($reg, $page, $matches);
        $stylesheet = file_get_contents($site.'/'.$matches[1]);
        // ob_start();
        // require($dir.'/deliver.php');
        // ob_get_clean();

        // get address of stylesheet

        // var_dump($matches[1]);
        // exit;
        // $stylesheet = $lia->resources->cache->get_cache_file_content($matches[1]);

        $out = preg_replace($reg,"<style>\n$stylesheet</style>", $page);

        $cache_dir = $dir.'/cache/';
        if (!is_dir($cache_dir))mkdir($cache_dir);
        $success = file_put_contents($out_file = $cache_dir.'/generic-error-page.html', $out);

        if ($success){
            echo "\nError page generated at $out_file!";
        } else {
            echo "\nError page generation FAILED :(";
        }
    },
    "Write error page to cache/generic-error-page.html by requesting /generic-error-page/ on localhost."
);


/**
 * Generate sitemap for phad ONLY. Does not make sitemap for any other routes.
 */
$cli->load_command('phad-sitemap',
    function($cli, $args){
        $err_rep = error_reporting();
        $_SERVER['REQUEST_URI'] = null;

        error_reporting(1|2|4);
        // echo "\nGenerating Sitemap File. Your deliver.php file MUST contain a var named \$server.";


        $_SERVER['REQUEST_URI'] = '/generic-error-page/';
        $_SERVER['HTTP_HOST'] = null;
        $_SERVER['REQUEST_METHOD'] = 'GET';

        $dir = getcwd();
        if (!is_file($dir.'/deliver.php'))$dir = $dir.'/test/Server/';

        ob_start();
        require($dir.'/deliver.php');
        ob_get_clean();

        if (!$lia->has('sitemap.dir')){
            throw new \Exception("You must set 'sitemap.dir' on lia. Like \$lia->set('sitemap.dir', \$THE_DIR)");
        }

        $full_list = $lia->get_all_sitemap_routes($sm_builder);

        // $sm_builder = new \Phad\SitemapBuilder($dir = $lia->get('sitemap.dir'));
        $dir = $lia->get('sitemap.dir');
        $sm_builder->dir = $dir;
        $sm_builder->host = R("Site.Url");
        $sm_file = $dir.'/sitemap.xml';
        $output_file = $sm_file;

        if (file_exists($sm_file)){
            unlink($sm_file);
        }
        $sm_builder->make_sitemap($full_list);

        $verify = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

        if (strpos(file_get_contents($output_file), $verify)!==false){
            echo "\nCreated sitemap file at:\n$output_file\n\n";
        } else {
            echo "\nFailed to create sitemap file at:\n$output_file\n\n";
        }

    }, "Generate sitemap of phad routes"
);

/**
 * Recompile all phad views
 * your deliver.php script MUST define `$server` and call `$server->enable_phad()`
 */
// $cli->load_command('recompile-phad',
//     function($cli, $args){
//         $err_rep = error_reporting();
//         $_SERVER['REQUEST_URI'] = null;
//
//         error_reporting(1|2|4);
//         echo "\nRecompiling Phad Views. Your deliver.php file MUST contain a var named \$server.";
//
//         $dir = getcwd();
//         if (!is_file($dir.'/deliver.php'))$dir = $dir.'/test/Server/';
//
//         require($dir.'/deliver.php');
//
//         if (!isset($server->phad)){
//             echo "\nYou MUST call \$server->enable_phad() in your deliver.php script in order to recompile phad items.\n";
//             return;
//         }
//
//
//         $server->phad->compile_all_items();
//
//         echo "\nRecompiling phad items DONE (hopefully, there is no verification currently)";
//     }, "Recompile all phad views",
// );

$cli->load_command('init-analytics',
    function($cli, $args){
        // $err_rep = error_reporting();
        $_SERVER['REQUEST_URI'] = NULL;
        $_SERVER['HTTP_HOST'] = NULL;
        $_SERVER['REQUEST_METHOD'] = 'GET';

        // error_reporting(1|2|4);
        echo "\nInitializing analytics table. Your deliver.php file MUST contain a var named \$lia.";

        $dir = getcwd();
        if (!is_file($dir.'/deliver.php'))$dir = $dir.'/test/Server/';

        try {
            require($dir.'/deliver.php');
        } catch (\Exception $e){
            //hopefully this is fine
        }

        if (!isset($lia->pdo)||!($lia->pdo instanceof \PDO)){
            echo "Your \$lia instance must have 'pdo' property on it.";
            return;
        }

        $lia->init_analytics_table($lia->pdo);

    }, "Create the analytics table in your database."
);

// $cli->load_command('new',
//     function($cli, $args){
//         $new = $args['--'][0] ?? null;
//         if ($new!='server'){
//             echo "Only supports 'new server' currently.";
//             return;
//         }
//
//         if (!$cli->ask("Create Server in ".$cli->pwd))return;
//
//         $path = dirname(__DIR__).'/test/Server/';
//         $from_path = $path;
//         $files = scandir($path);
//         unset($files[0]);
//         unset($files[1]);
//         foreach ($files as $child){
//             if (is_dir($path.'/'.$child)&&$child!='.'&&$child!='..'){
//                 $children = scandir($path.'/'.$child);
//                 foreach ($children as $last){
//                     if ($last=='.'||$last=='..') continue;
//                     $files[] = $child.'/'.$last;
//                 }
//                 continue;
//             }
//         }
//
//         $to_path = $cli->pwd;
//         foreach ($files as $f){
//             $in_path = $from_path.'/'.$f;
//             $out_path = $to_path.'/'.$f;
//             // echo "\n$out_path\n";
//
//             if (is_file($in_path)){
//                 if (is_file($out_path)&&(isset($args['all'])||!$cli->ask("Overwrite $f?")))continue;
//                 else if (isset($args['ask'])&&!$cli->ask("Write ".$f))continue;
//                 copy($in_path, $out_path);
//             } else if (is_dir($in_path)){
//                 if (!is_dir($out_path)
//                     &&(
//                         !isset($args['ask'])
//                         ||$cli->ask("mkdir ".$f)
//                     )
//                     )mkdir($out_path);
//             }
//
//         }
//     }, "new server --all to overwrite all files without prompts or --ask to ask for every file copy"
// );
//



/**
 * Execute a CREATE TABLE statement for a phad item. pass the item name.
 * @arg item_name
 */
$cli->load_command('new-phad-table',
    function($cli, $args){
        $err_rep = error_reporting();
        $_SERVER['REQUEST_URI'] = null;

        error_reporting(1|2|4);
        // echo "\nGenerating Sitemap File. Your deliver.php file MUST contain a var named \$server.";


        $_SERVER['REQUEST_URI'] = '/generic-error-page/';
        // setting http_host to localhost causes Lia\Simple->is_production() to return `true` 
        $_SERVER['HTTP_HOST'] = 'localhost';
        $_SERVER['REQUEST_METHOD'] = 'GET';

        $dir = getcwd();
        if (!is_file($dir.'/deliver.php'))$dir = $dir.'/test/Server/';

        ob_start();
        require($dir.'/deliver.php');
        ob_get_clean();

        $item = $lia->phad($args['--'][0]);
        $item->args['phad']->force_allow_access = true;

        $statement = $item->create_table_statement();

        echo "\n";
        echo $statement;
        echo "\n";

        if (isset($args['exec'])&&isset($lia->pdo)){
            $lia->pdo->exec($statement);
            echo "\n\nSTATEMENT EXECUTED\n\n";
        } 
    }, "Print a CREATE TABLE statement for a phad item. pass the item name. pass --exec to also execute the statement."
);



/**
 * Backup your db using mysqldump
 * @arg rel_file_name the relative path to the file name to store the backup in or nothing to use the default
 */
$cli->load_command('backup-db',
    function($cli, $args){
        $err_rep = error_reporting();
        $_SERVER['REQUEST_URI'] = null;

        error_reporting(1|2|4);
        // echo "\nGenerating Sitemap File. Your deliver.php file MUST contain a var named \$server.";


        $_SERVER['REQUEST_URI'] = '/generic-error-page/';
        $_SERVER['HTTP_HOST'] = null;
        $_SERVER['REQUEST_METHOD'] = 'GET';

        $dir = getcwd();
        if (!is_file($dir.'/deliver.php'))$dir = $dir.'/test/Server/';

        ob_start();
        require($dir.'/deliver.php');
        ob_get_clean();

        $file = $args['--'][0] ?? 'db-backup-'.date('y-m-d_h\mi').'.sql';
        $file = getcwd().'/'.$file;

        if (is_dir($file)){
            $file = $file.'/db-backup-'.date('y-m-d_h\mi').'.sql';
        }

        $user = $lia->env->get('mysql.user');
        $password = $lia->env->get('mysql.password');
        $database = $lia->env->get('mysql.dbname');

        $host = $lia->env->get('mysql.host');

        passthru("mysqldump -h $host -u $user -p$password $database > \"$file\"");


    }, "mysqldump and backup your database. Optionally pass relative file name to store the backup in"
);


/**
 * Restore your database from an sql file, presumably from a mysqldump
 * @arg rel_file_name the relative path to the file name or directory. If directory, will prompt for sql file. If nothing, will use current working directory.
 * @arg which_file a numeric index of the file to load
 */
$cli->load_command('restore-db',
    function($cli, $args){
        $err_rep = error_reporting();
        $_SERVER['REQUEST_URI'] = null;

        error_reporting(1|2|4);
        // echo "\nGenerating Sitemap File. Your deliver.php file MUST contain a var named \$server.";


        $_SERVER['REQUEST_URI'] = '/generic-error-page/';
        $_SERVER['HTTP_HOST'] = null;
        $_SERVER['REQUEST_METHOD'] = 'GET';

        $dir = getcwd();
        if (!is_file($dir.'/deliver.php'))$dir = $dir.'/test/Server/';

        ob_start();
        require($dir.'/deliver.php');
        ob_get_clean();

        $dir = $args['--'][0] ?? '';
        $dir = getcwd().'/'.$dir;
        // var_dump($dir);
        // exit;
        if (is_file($dir)){
            // $file = $dir;
            $dir = getcwd();
            $file = $args['--'][0] ?? '';
        } else {
            $list = scandir($dir);
            $list = array_filter($list, function($file){if (substr($file,-4)=='.sql')return true; return false;});

            $list = array_values($list);
            echo "Files:";
            foreach ($list as $index=>$file){
                echo "\n$index: $file";
            }
            echo "\n";

            $answer = $args['--'][1] ?? null;
            if ($answer==null){
                if (!function_exists('readline')){
                    echo "readline() not available. Run the command again passing the relative dir AND the file index to restore from.";
                    return;
                }
                $answer = readline("Enter number of file to restore from: ");
            }
            $file = $list[$answer];
        }

        $lia->pdo->exec(file_get_contents($dir.'/'.$file));


    }, "Restore database from .sql file. Pass relative directory or file path."
);


/**
 * Generate routes from phad items
 */
$cli->load_command('phad-routes',
    function($cli, $args){
        $err_rep = error_reporting();
        $_SERVER['REQUEST_URI'] = null;

        error_reporting(1|2|4);
        // echo "\nGenerating Sitemap File. Your deliver.php file MUST contain a var named \$server.";


        $_SERVER['REQUEST_URI'] = '/generic-error-page/';
        $_SERVER['HTTP_HOST'] = null;
        $_SERVER['REQUEST_METHOD'] = 'GET';

        $dir = getcwd();
        if (!is_file($dir.'/deliver.php'))$dir = $dir.'/test/Server/';

        ob_start();
        require($dir.'/deliver.php');
        ob_get_clean();

        if (!$lia->has('sitemap.dir')){
            throw new \Exception("You must set 'sitemap.dir' on lia. Like \$lia->set('sitemap.dir', \$THE_DIR)");
        }

        $host = R("Site.Url") ?? false;
        if ($host==false){
            throw new \Exception("You must set 'Site.Url' in your RSettings.json file");
        }

        $full_list = [];
        $count = 0;
        foreach ($lia->phads as $phad){
            $phad->routes_from_cache(true);
            $count++;
        }

        echo "\nRoutes regenerated for {$count} phad objects";

    }, "Re-generate a cache of all phad routes"
);


/**
 * Setup server template files in the current directory
 */
$cli->load_command('init-server',
    function($cli, $args){
        $err_rep = error_reporting();
        $_SERVER['REQUEST_URI'] = null;

        error_reporting(1|2|4);
        // echo "\nGenerating Sitemap File. Your deliver.php file MUST contain a var named \$server.";

        if (!$cli->ask("Copy server files to ".$cli->pwd."")){
            return;
        }


        if (!$cli->ask("Existing files will be overwritten! Do you consent?")){
            return;
        }

        $source_dir = dirname(__DIR__).'/test/ServerSimple/';
        passthru("cp --recursive \"$source_dir\"/* \"".$cli->pwd."\"");

    }, "Setup server template files in the current directory"
);

$cli->execute();