<?php

namespace App\Console\Commands;
use App\Virtual;
use Illuminate\Console\Command;
Use \Carbon\Carbon;
use App\Server;

class MakeVirtuals extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'virtuals:create';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Goes throught database and create virtuals';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        echo date('Y-m-d H:i:s') . ': Checking database for new virtuals ' . PHP_EOL; 
        $virtualsReady = Virtual::where([
            ['ready', '=', '1'],
        ])->get();

        //Change for use of private keys
        //$usekey="-i $server->private";
        $usekey="";

        foreach($virtualsReady as $virtual) {
            $name = $virtual->user_name . '_' . $virtual->system; 
            if ($virtual->server_id=="0")
            {
                echo("Server for virtual ".$name." not set");
                break;
            }
            $server = Server::where('id', $virtual->server_id)->first();
            $tmp = exec("ping -n 1 -w 1 $server->ip");
            if(!strpos($tmp, "100% loss")){
            echo ("Server ".$server->ip." is online, ". "trying to create ".$name .PHP_EOL);
            if (($virtual->switch=="No network available")||($virtual->switch=="Server offline"))
            {
                echo("Virtual network not set");
                break;
            }
            
            if($server->type=="ESXi") {
                $clone=$server->scripts."/clone.sh";
                $memory=$virtual->memory*1024;
                $disk=$virtual->disk;
                $tmp = exec("ssh $usekey -oNumberOfPasswordPrompts=0 root@$server->ip [ -f $clone ] && echo Found || echo Not");
                if ($tmp=="Not")
                {
                    echo("Failed to connect to $server->ip");
                    continue;
                }
                if ($tmp == "Found") {
                    $tmp = exec("ssh $usekey -oNumberOfPasswordPrompts=0 root@$server->ip [ -d $server->templates ] && echo Found || echo Not");
                    if ($tmp=="Not")
                        {   echo("Failed to find directory $server->templates"); continue; }
                    $tmp = exec("ssh $usekey -oNumberOfPasswordPrompts=0 root@$server->ip [ -d $server->clones ] && echo Found || echo Not");
                    if ($tmp=="Not")
                        {   echo("Failed to find directory $server->clones "). PHP_EOL; }

                    $tmp = $clone." ".$virtual->system." ".$name." ".$memory." ".$virtual->cpu." ".$disk." ".$server->templates." ".$server->clones." '".$virtual->switch."'";
                    $tmp = exec("ssh $usekey root@$server->ip $tmp & exit");
                    if (strpos($tmp, "not found"))
                    {
                        echo("System with name: ".$virtual->system." not found");
                    }
                    if ( is_numeric($tmp) ) {
                            echo ('virtual created with ID ' .$tmp .PHP_EOL);
                            Virtual::where([
                                ['id', '=',  $virtual->id],
                            ])->update(['ready' => '2']);
                        }
                    }
                } #END ESXi

                if($server->type=="HyperV") {
                    $clone=$server->scripts."\clone.ps1";
                    $memory=$virtual->memory."GB";
                    $disk=$virtual->disk."GB";
                    $tmp = Shell_Exec("ssh $usekey -oNumberOfPasswordPrompts=0 administrator@$server->ip powershell.exe Test-Path $clone");                                 
                    if ($tmp == "False\n")
                    {   echo("Failed to find $clone"); continue; }

                    $tmp = "powershell.exe ".$clone." ".$virtual->system." ".$name." "
                            .$memory." ".$virtual->cpu." ".$disk." ".$server->templates." ".$server->clones." '".$virtual->switch."'";
                    $tmp = Shell_Exec("ssh $usekey administrator@$server->ip $tmp& exit");
                    echo($tmp);
                    $check=$server->scripts."\check.ps1";
                    $tmp = Shell_Exec("ssh $usekey administrator@$server->ip powershell.exe $check $name & exit");
                    if (strpos($tmp, 'Operating normally') !== false) {
                        echo ('virtual '.$name . " created" .PHP_EOL);
                        Virtual::where([
                            ['id', '=',  $virtual->id],
                        ])->update(['ready' => '2']);
                    }
                } #END HyperV                
            } else {
                echo ("Server ".$server->ip." is offline cant create virtual ". $name.PHP_EOL);
            }
        }      
    }
}
