#!/usr/bin/php
<?php
// # Copy this script to where you can easily access or where you wish to always initialize you projects
// # To use this script, open your terminal or command line (cmd) and type `php init-lay`
// # Use; `php init-lay -h` for to see options available to you

$ag = $argv;
$s = DIRECTORY_SEPARATOR; // this is '\' for windows and '/' for linux, mac or UNIX systems

// You may modify this section if you wish
$overwrite_existing_project_by_default = false;
$always_update_lay_package = true;
$default_lay_location = "{$s}var{$s}www{$s}Lay"; // change this to the location of your Lay package

require_once $default_lay_location . $s . "init-lay-res" . $s . "Core.php";
$core = new Core($argv, $default_lay_location);

if($argc == 1)
    $core->help(true);

if($ag[1] == "-h" || $ag[1] == "--help")
    $core->help();

if(substr($ag[1],0,1) == "-")
    $core->use_error("Project location cannot start with '-', if you wish to bypass that, add a `forward slash (/) to it`");

$overwrite_project = $overwrite_existing_project_by_default;
$update_project = $always_update_lay_package;

for($i = 0; $i < $argc; $i++){
    $core->set_flags($i, $default_lay_location, $overwrite_project, $update_project);
}

// start process
$project_root = ltrim($ag[1],"/");
$core->set_current_project($project_root);
$core->set_project_name($project_root);
$core->set_update_lay($update_project);
$core->set_overwrite($overwrite_project);

$lay = rtrim($default_lay_location, $s) . $s;
$project_name = $core->project_name;

if(!is_dir($default_lay_location))
    $core->use_error("The specified `default_lay_location` '$default_lay_location' does not exist, please change the value to the place where you cloned the `Lay` package into and try again");

if(!is_dir($project_root)) {
    print "-- New Project [$project_name] Creation Initiated\n";
        $core->create_project($lay, $project_root);
        exec("composer install --working-dir=$project_root --no-dev");
    print "   [$project_name] Creation Completed\n";
    return;
}

$core->project_exists();

print "-- Starting [$project_name] Modification\n";

$overwrite = !($overwrite_existing_project_by_default === false && $overwrite_project === false);
$update = !($always_update_lay_package === false && $update_project === false);

$msg = $overwrite ? "Overwritten" : "Updated";

if(!$overwrite && !$update)
    $core->use_error(
        "You are trying to overwrite an existing project, please rename the existing folder or change the name of your current project location.\n".
        "If you really want to overwrite the project, use add flag `-w true` to your command."
    );

if(!$update)
    $core->use_error(
        "You are trying to update the lay package of your project, if this is your wish add the flag `-u true` to your command"
    );

$core->create_project($lay, $project_root);

exec("composer update --working-dir=$project_root --no-dev");

print "   [$project_name] $msg Successfully\n";
