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

define('ROOT_PATH', dirname(__DIR__) . DIRECTORY_SEPARATOR);

/**
 * Removes a directory and all it's files
 *
 * @param string $path Directory Path
 */
function removeDirectory($path)
{
    $files = glob($path . '/*');
    foreach ($files as $file) {
        is_dir($file) ? removeDirectory($file) : unlink($file);
    }
    rmdir($path);
}

/**
 * Returns the operating system type
 *
 * @return string
 */
function getOperatingSystem()
{
    $uname = strtolower(php_uname());
    if (strpos($uname, "darwin") !== false) {
        return 'osx';
    } else if (strpos($uname, "win") !== false) {
        return 'windows';
    } else if (strpos($uname, "linux") !== false) {
        return 'linux';
    }

    return 'unknown';
}

/**
 * Checks installation requirements
 *
 * @return bool
 */
function isInstallationRequirementsValid()
{
    $validations = [];
    $validationRequirementLength = 30;
    $validationStatusLength = 10;

    // PHP VERSION
    $validation = [];
    $phpRequiredVersion = '5.5.9';
    $phpVersion = phpversion();
    $isVersionValid = version_compare($phpRequiredVersion, $phpVersion, '<=') ? 'OK' : 'NOK';

    $validation['requirement'] = str_pad('PHP version ' . $phpRequiredVersion, $validationRequirementLength, ' ', STR_PAD_RIGHT);
    $validation['status'] = str_pad($isVersionValid, $validationStatusLength, ' ', STR_PAD_RIGHT);
    $validation['extra'] = 'Your version ' . $phpVersion . PHP_EOL;

    $validations[] = $validation;

    // GD LIBRARY
    $validation = [];
    $isGDInstalledValid = extension_loaded('gd') && function_exists('gd_info') ? 'OK' : 'NOK';

    $validation['requirement'] = str_pad('PHP GD library', $validationRequirementLength, ' ', STR_PAD_RIGHT);
    $validation['status'] = str_pad($isGDInstalledValid, $validationStatusLength, ' ', STR_PAD_RIGHT);

    $validations[] = $validation;

    // EXEC FUNCTION
    $validation = [];
    $disabledFunctions = explode(',', ini_get('disable_functions'));
    $isExecValid = !in_array('exec', $disabledFunctions) ? 'OK' : 'NOK';

    $validation['requirement'] = str_pad('exec function enabled', $validationRequirementLength, ' ', STR_PAD_RIGHT);
    $validation['status'] = str_pad($isExecValid, $validationStatusLength, ' ', STR_PAD_RIGHT);

    $validations[] = $validation;

    // PHP ZIP EXTENSION
    $validation = [];
    $isZipValid = class_exists('ZipArchive') ? 'OK' : 'NOK';

    $validation['requirement'] = str_pad('PHP Zip module enabled', $validationRequirementLength, ' ', STR_PAD_RIGHT);
    $validation['status'] = str_pad($isExecValid, $validationStatusLength, ' ', STR_PAD_RIGHT);
    $validation['extra'] = 'Used only on setup' . PHP_EOL;

    $validations[] = $validation;

    echo '*** Web Photographer ***' . PHP_EOL;
    echo 'Your server need to match this requirements:' . PHP_EOL . PHP_EOL;

    echo str_pad('REQUIREMENT', $validationRequirementLength, ' ', STR_PAD_RIGHT);
    echo str_pad('STATUS', $validationStatusLength, ' ', STR_PAD_RIGHT);
    echo 'EXTRA' . PHP_EOL;

    foreach ($validations as $val) {
        echo $val['requirement'];
        echo $val['status'];
        echo isset($val['extra']) ? $val['extra'] : '' . PHP_EOL;
    }

    echo PHP_EOL;

    return $isVersionValid == 'OK' && $isGDInstalledValid == 'OK' && $isExecValid == 'OK' && $isZipValid == 'OK';
}

/**
 * Removes all the installation/temporary files
 */
function removeInstallationFiles($cleanup = false)
{
    if (!$cleanup) {
        if (file_exists(ROOT_PATH . 'bin/phantomjs')) {
            unlink(ROOT_PATH . 'bin/phantomjs');
        }
        if (file_exists(ROOT_PATH . 'bin/phantomjs.exe')) {
            unlink(ROOT_PATH . 'bin/phantomjs.exe');
        }
    }

    if (file_exists(ROOT_PATH . 'PhanthomJS.zip')) {
        unlink(ROOT_PATH . 'PhanthomJS.zip');
    }
    if (file_exists(ROOT_PATH . 'PhanthomJS.tar.bz2')) {
        unlink(ROOT_PATH . 'PhanthomJS.tar.bz2');
    }
    if (is_dir(ROOT_PATH . 'tmp')) {
        removeDirectory(ROOT_PATH . 'tmp');
    }
    if (is_dir(ROOT_PATH . 'phantomjs-2.1.1-linux-x86_64')) {
        removeDirectory(ROOT_PATH . 'phantomjs-2.1.1-linux-x86_64');
    }
    if (is_dir(ROOT_PATH . 'phantomjs-2.1.1-linux-i686')) {
        removeDirectory(ROOT_PATH . 'phantomjs-2.1.1-linux-i686');
    }
}

function createDirectories()
{
    if (!file_exists(ROOT_PATH . 'public/images/printscreen/')) {
        mkdir(ROOT_PATH . 'public/images/printscreen/', 0777, true);
    }
    if (!file_exists(ROOT_PATH . 'public/images/showcase/')) {
        mkdir(ROOT_PATH . 'public/images/showcase/', 0777, true);
    }
}

if (!isInstallationRequirementsValid()) {
    exit(1);
}

echo 'Preparing installation...' . PHP_EOL;
removeInstallationFiles();
echo 'Installing...' . PHP_EOL;

switch (getOperatingSystem()) {
    case 'windows':
        $remoteUrl = 'https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-windows.zip';
        $result = file_put_contents(ROOT_PATH . 'PhanthomJS.zip', fopen($remoteUrl, 'r'));

        $zip = new ZipArchive;
        if (!$result || $zip->open(ROOT_PATH . 'PhanthomJS.zip') !== true) {
            echo 'Failed to open PhanthomJS.zip';
            exit(1);
        }

        $zip->extractTo(ROOT_PATH . 'tmp');
        $zip->close();

        if (!copy(ROOT_PATH . 'tmp/phantomjs-2.1.1-windows\bin\phantomjs.exe', ROOT_PATH . 'bin/phantomjs.exe')) {
            echo 'Failed to copy the phantomjs.exe file';
            exit(1);
        }

        touch(ROOT_PATH . 'storage/logs/laravel.log');
        break;

    case 'linux':
        shell_exec('chmod 777 -R .');
        $arch = trim(shell_exec('arch'));

        if ($arch == "x86_64") {
            shell_exec('wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2 -O PhanthomJS.tar.bz2');
            shell_exec('tar -jxvf ' . ROOT_PATH . 'PhanthomJS.tar.bz2');
            shell_exec('mv ' . ROOT_PATH . 'phantomjs-2.1.1-linux-x86_64/bin/phantomjs ' . ROOT_PATH . 'bin/phantomjs');
        } else {
            shell_exec('wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-i686.tar.bz2 -O PhanthomJS.tar.bz2');
            shell_exec('tar -jxvf ' . ROOT_PATH . 'PhanthomJS.tar.bz2');
            shell_exec('mv ' . ROOT_PATH . 'phantomjs-2.1.1-linux-i686/bin/phantomjs ' . ROOT_PATH . 'bin/phantomjs');
        }

        shell_exec('chmod +x ' . ROOT_PATH . 'bin/phantomjs');

        // Check permissions
        shell_exec('touch ' . ROOT_PATH . 'storage/logs/laravel.log');
        shell_exec('chmod 777 -R .');
        break;

    case 'osx':
        shell_exec('chmod 777 -R ' . ROOT_PATH);

        $remoteUrl = 'https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-macosx.zip';
        $result = file_put_contents(ROOT_PATH . 'PhanthomJS.zip', fopen($remoteUrl, 'r'));

        $zip = new ZipArchive;
        if (!$result || $zip->open(ROOT_PATH . 'PhanthomJS.zip') !== true) {
            echo 'Failed to open PhanthomJS.zip';
            exit(1);
        }

        $zip->extractTo(ROOT_PATH . 'tmp');
        $zip->close();

        if (!copy(ROOT_PATH . 'tmp/phantomjs-2.1.1-macosx/bin/phantomjs', ROOT_PATH . 'bin/phantomjs')) {
            echo 'Failed to copy the phantomjs.exe file';
            exit(1);
        }

        shell_exec('chmod +x ' . ROOT_PATH . 'bin/phantomjs');

        touch(ROOT_PATH . 'storage/logs/laravel.log');
        break;

    default:
        echo 'It was not possible to determine your operating system, please contact the support team and refer your issue' . PHP_EOL;
        exit(1);
}

createDirectories();

echo 'Cleaning up installation files...' . PHP_EOL;
removeInstallationFiles(true);

echo 'Done!! Now you can use Web Photographer.';
