#!/usr/bin/env php

<?php

if (!file_exists('/var/www/html/.env')) {
    die;
}

$cmd = getopt("", ["sqlite", "mysql", "mariadb", "pgsql", "shared"]);

$key = shell_exec("openssl rand -base64 32 | tr -d '=' | tr -d '+'  | tr -d '/' | tr -d ' '");
$key = substr($key, 0, 32);
$database_url = null;
$getCreds = true;
$creds = null;

$http_port = readline("What port do you want the server to listen on (80)? ");
$http_port = (empty($http_port) ? 80 : $http_port);

if (isset($cmd['sqlite'])) {
    $database_url = "DATABASE_URL=\"sqlite:////data/data.db\"";
    $getCreds = false;
} elseif (isset($cmd['mysql'])) {
    $database_url = "DATABASE_URL=\"mysql://\${DB_USER}:\${DB_PASS}@\${DB_HOST}:\${DB_PORT}/\${DB_NAME}?charset=utf8&use_unicode=1\"";
} elseif (isset($cmd['mariadb'])) {
    $database_url = "DATABASE_URL=\"mysql://\${DB_USER}:\${DB_PASS}@\${DB_HOST}:\${DB_PORT}/\${DB_NAME}?charset=utf8mb4\"";
} elseif (isset($cmd['pgsql'])) {
    $database_url = "DATABASE_URL=\"postgresql://\${DB_USER}:\${DB_PASS}@\${DB_HOST}:\${DB_PORT}/\${DB_NAME}?sslmode=disable\"";
}

if (is_null($database_url)) {
    $getCreds = false;
    die("When calling this make sure that you enter a database type");
}

if ($getCreds) {
    $dbInfo = null;
    if (isset($cmd['shared'])) {
        $db_host = readline("DB Host: ");
        $db_port = readline("DB Port: ");
        $db_name = readline("DB Schema: ");
        $db_user = readline("DB User: ");

        print "DB Password: ";
        // Disable echoing of input characters
        system('stty -echo');
        // Read the password from standard input
        $db_password = trim(fgets(STDIN));
        // Re-enable echoing of input characters
        system('stty echo');
    } else {
        $db_host = 'db';
        $db_port = (isset($cmd['pgsql']) ? 5432 : 3306);
        $db_name = 'sermon_notes';
        $db_user = 'root';
        $pwd = shell_exec("openssl rand -base64 32 | tr -d '=' | tr -d '+'  | tr -d '/' | tr -d ' '");
        $db_password = substr($pwd, 0, 32);

        if (isset($cmd['pgsql'])) {
            $dbInfo = <<<INFO
            POSTGRES_USER=$db_user
            POSTGRES_PASSWORD=$db_password
            
            INFO;
        } elseif (isset($cmd['mysql']) || isset($cmd['mariadb'])) {
            $dbInfo = <<<INFO
            MYSQL_ROOT_PASSWORD=$db_password

            INFO;
        }
    }
    
    $creds = <<<CREDS
    DB_HOST=$db_host
    DB_PORT=$db_port
    DB_NAME=$db_name
    DB_USER=$db_user
    DB_PASS=$db_password
    $dbInfo

    CREDS;
}

$output = <<<EOF
APP_ENV=prod
APP_DEBUG=0
APP_SECRET=$key
MESSENGER_TRANSPORT_DSN=doctrine://default?auto_setup=0
MAILER_DSN=null://null
HTTP_PORT=$http_port
$creds$database_url

EOF;

file_put_contents('/var/www/html/.env', $output);
