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

/**
 * Class wookteamLoader
 */
class wookteamLoader
{
    function modifyEnv(array $data)
    {
        if (empty($data) || !is_array($data)) {
            return false;
        }
        $envPath = realpath(__DIR__ . '/../') . DIRECTORY_SEPARATOR . '.env';
        if (!file_exists($envPath)) {
            return false;
        }
        $envContent = file_get_contents($envPath);
        foreach ($data as $key => $val) {
            $envContent = preg_replace("/^" . $key . "\s*=\s*(.*?)$/m", $key . "=" . $val, $envContent);
        }
        file_put_contents($envPath, $envContent);
        return true;
    }

    function modifyWookteam($type)
    {
        $envPath = realpath(__DIR__ . '/../') . DIRECTORY_SEPARATOR . '/docker/php.conf';
        if (!file_exists($envPath)) {
            return false;
        }
        $envContent = file_get_contents($envPath);
        $envContent = str_replace("#command=php bin/laravels start -i", "command=php bin/laravels start -i", $envContent);
        $envContent = str_replace("#command=./bin/inotify ./app", "command=./bin/inotify ./app", $envContent);
        if ($type == "dev") {
            $envContent = str_replace("command=php bin/laravels start -i", "#command=php bin/laravels start -i", $envContent);
        } else {
            $envContent = str_replace("command=./bin/inotify ./app", "#command=./bin/inotify ./app", $envContent);
        }
        file_put_contents($envPath, $envContent);
        return true;
    }
}

$array = getopt('', ['port:', 'ssl:', 'wookteam:']);
$loader = new wookteamLoader();
if (isset($array['wookteam'])) {
    $loader->modifyWookteam($array['wookteam']);
} else {
    $data = [];
    if (isset($array['port'])) {
        $data['APP_PORT'] = $array['port'] ?: '8000';
    }
    if (isset($array['ssl'])) {
        $data['APP_PORT_SSL'] = $array['ssl'] ?: '44300';
    }
    if ($data) {
        $loader->modifyEnv($data);
    }
}

