<?php
$success = '';
$divErrors = '';

function postInput($data)
{
    if (!isset($data)) {
        return '';
    }
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

function checkPost($value)
{
    return (isset($_POST[$value])) ? $_POST[$value] : null;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $serverFolder = realpath(dirname(dirname(__FILE__)));
    $publicFolder = basename(dirname(dirname(__FILE__)));
    $installFolderPath = realpath(dirname(dirname(dirname(__FILE__))));

    $filenameCert = $_POST['filenameCert'];
    $filenameKey = $_POST['filenameKey'];
    $secretApiKey = $_POST['apisecret'];

    $videoApi = postInput($_POST['videoApi']);
    $audioApi = postInput($_POST['audioApi']);
    $apiKeyDid = postInput($_POST['apiKeyDid']);
    $chatGptApi = postInput($_POST['chatgpt']);
    $apiKeyOpenrouter = postInput($_POST['apiKeyOpenrouter']);
    $apiKeyAnakin = postInput($_POST['apiKeyAnakin']);

    $servername = 'localhost';
    $database = $_POST['database'];
    $username = $_POST['username'];
    $password = $_POST['password'];
    $charset = 'utf8mb4';
    $dbPrefix = '';
    $errors = array();

    $output = shell_exec('node -v');
    $curNumber = str_replace('v', '', $output);
    $curNumber = explode('.', $curNumber);
    if (!isset($curNumber[0]) || $curNumber[0] < 16) {
        array_push($errors, 'Node version not suitable or Node is missing. You need to install it.<br/>');
    }

    if (!is_dir($serverFolder) && !is_dir($serverFolder . '/config')) {
        array_push($errors, 'Server folder is not correct. Make sure the folder exists and your Server files are there.<br/>');
    }

    $compare = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $explodeUrl = explode('/install', $compare);

    $serverURL = $explodeUrl[0];


//    if (!file_exists($filenameCert)) {
//        array_push($errors, 'Certificate file you provided is missing. Please make sure file location is properly provided.<br/>');
//    }
//
//    if (!file_exists($filenameKey)) {
//        array_push($errors, 'Key file you provided is missing. Please make sure file location is properly provided.<br/>');
//    }

    $dsn = "mysql:host=$servername;dbname=$database;charset=$charset";
    $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ];

    try {
        $pdo = new PDO($dsn, $username, $password, $options);
    } catch (\PDOException $e) {
        if ($e->getCode() == 1045) {
            array_push($errors, 'Provided MySQL credentials are not proper.<br/>');
        } else if ($e->getCode() == 1049) {
            array_push($errors, 'Provided MySQL database is not existing.<br/>');
        } else if ($e->getCode() == 2002) {
            array_push($errors, 'Cannot connect to the host. Make sure your DB can access remote connections.<br/>');
        } else {
            array_push($errors, $e->getMessage() . '<br/>');
        }
    }

    if (count($errors) > 0) {
        foreach ($errors as $error) {
            $divErrors .= $error;
        }
    } else {

        $serverURL = str_replace('www.', '', $serverURL);
        $stripUrlArr = explode('/', str_replace('https://', '', $serverURL));
        $stripUrl = $stripUrlArr[0];
        $serverIP = gethostbyname($stripUrl);

        $sql = file_get_contents('../server/dump.sql');
        $sql .= file_get_contents('../server/dump_1.0.2.sql');
        $sql .= file_get_contents('../server/dump_1.0.3.sql');
        $sql .= file_get_contents('../server/dump_1.0.4.sql');
        $sql .= file_get_contents('../server/dump_1.0.11.sql');
        $sql .= file_get_contents('../server/dump_1.0.12.sql');
        $sql .= file_get_contents('../server/dump_1.0.17.sql');
        $sql .= file_get_contents('../server/dump_1.0.18.sql');
        $sql .= file_get_contents('../server/dump_1.0.19.sql');
        $sql .= file_get_contents('../server/dump_1.0.20.sql');
        $sql .= file_get_contents('../server/dump_1.0.21.sql');
        $sql .= file_get_contents('../server/dump_1.0.22.sql');
        $pdo->exec($sql);

        //server/connect.php file
        $phpContent = file_get_contents($serverFolder . '/server/connect.php');
        $str = str_replace('$database = \'\';', '$database = \'' . $database . '\';', $phpContent);
        $str = str_replace('$username = \'\';', '$username = \'' . $username . '\';', $str);
        $str = str_replace('$password = \'\';', '$password = \'' . $password . '\';', $str);
        $str = str_replace('$apiKey = \'\';', '$apiKey = \'' . $secretApiKey . '\';', $str);
        if (file_put_contents($serverFolder . '/server/connect.php', $str) == false) {
            array_push($errors, 'Error writing to connect.php file. Make sure files in Server folder are not with root ownershi.<br/>');
        }

        if (count($errors) == 0) {
            $success .= 'Database setup successfully finished!<br/>';
        }

        $phpContent = file_get_contents($installFolderPath . '/src/config.js');
        $str = str_replace("/SSL_CERT_PATH", $filenameCert, $phpContent);
        $str = str_replace("/SSL_KEY_PATH", $filenameKey, $str);
        $str = str_replace("API_KEY_SECRET", $secretApiKey, $str);
        if ($chatGptApi) {
            $str = str_replace("CHAT_GPT_KEY", $chatGptApi, $str);
            $str = str_replace("enabled: false", "enabled: true", $str);
        }
        if ($videoApi) {
            $str = str_replace("VIDEO_AVATAR_KEY", $videoApi, $str);
            $str = str_replace("VIDEO_AVATAR_STREAM_KEY", $videoApi, $str);
            $str = str_replace("enabled: false", "enabled: true", $str);
        }
        if ($audioApi) {
            $str = str_replace("ELEVEN_LABS_KEY", $audioApi, $str);
            $str = str_replace("enabled: false", "enabled: true", $str);
        }
        if ($apiKeyDid) {
            $str = str_replace("DID_VIDEO_AVATAR_KEY", $apiKeyDid, $str);
            $str = str_replace("enabled: false", "enabled: true", $str);
        }
        if ($apiKeyOpenrouter) {
            $str = str_replace("OPENROUTER_API_KEY", $apiKeyOpenrouter, $str);
            $str = str_replace("enabled: false", "enabled: true", $str);
        }
        if ($apiKeyAnakin) {
            $str = str_replace("ANAKIN_AI_KEY", $apiKeyAnakin, $str);
            $str = str_replace("enabled: false", "enabled: true", $str);
        }
        $str = str_replace("'public'", "'".$publicFolder."'", $str);
        $str = str_replace("announcedIp: getLocalIp()", "announcedIp: '".$_SERVER['SERVER_ADDR']."'", $str);
        $str = str_replace("const IPv4 = getIPv4();", "const IPv4 = '".$_SERVER['SERVER_ADDR']."'", $str);
        if (file_put_contents($installFolderPath . '/src/config.js', $str) == false) {
            array_push($errors, 'Error writing to src/config.js file. Make sure files in this folder are not with root ownership.<br/>');
        }
        copy('script_ubuntu.sh', $installFolderPath.'/script_ubuntu.sh');

        $phpContent = file_get_contents($serverFolder . '/client.html');
        $str = str_replace('YOUR_DOMAIN', $stripUrl, $phpContent);
        if (file_put_contents($serverFolder . '/client.html', $str) == false) {
            array_push($errors, 'Error writing to sample HTML client.html file. Make sure files in LiveSmart folder are not with root ownership.<br/>');
        }
        if (count($errors) == 0) {
            $success .= 'Configuration file successfully generated!<br/>';
        }

        if (count($errors) == 0) {
            $success .= 'Now you have to login to your console/terminal with root user, go to main folder at ' . $installFolderPath . ' and run the installation script from there <code>sudo bash script_ubuntu.sh</code><br/>';
            $success .= 'Make sure your port 9002 is opened for TCP and port ranges 40000-40100 are opened for TCP and UDP traffic.<br/>';
            $success .= 'Then add the following code to your web server config file:<br/>
                        If you are on Apache, add this for 443 virtual host: <br/>
                        <pre>
                        ProxyRequests off
                        SSLProxyEngine on
                        SSLProxyVerify none
                        SSLProxyCheckPeerCN off
                        SSLProxyCheckPeerName off
                        SSLProxyCheckPeerExpire off
                        ProxyPreserveHost On
                        &lt;Location "/"&gt;
                            Order allow,deny
                            Allow from all
                            ProxyPass https://localhost:9002/
                            ProxyPassReverse https://localhost:9002/
                        &lt;/Location&gt;
                        &lt;Location "/dash"&gt;
                            ProxyPass "!"
                            Order allow,deny
                            Allow from all
                        &lt;/Location&gt;
                        &lt;Location "/server"&gt;
                            ProxyPass "!"
                            Order allow,deny
                            Allow from all
                        &lt;/Location&gt;
                        </pre>
                        and this if you are on Nginx: 
                        <pre>
                        location / {
                            proxy_set_header X-Real-IP $remote_addr;
                            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                            proxy_set_header X-NginX-Proxy true;
                            proxy_pass https://localhost:9002/;
                            proxy_ssl_session_reuse off;
                            proxy_set_header Host $http_host;
                            proxy_cache_bypass $http_upgrade;
                            proxy_redirect off;
                        }
                        location /dash {
                        }
                        location /server {    
                        }</pre> and then restart web server.<br/>';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>Installation wizard</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
        <style>
            .bs-example{
                padding-top: 5px;
                margin: auto;
                width: 900px;
            }
        </style>
    </head>
    <body>
        <div class="bs-example">
            <p>
                Welcome to installation wizard! This script applies for Ubuntu/Debian operating systems. In order to fully install this product on your server, you need:<br/>
                - some basic knowledge of Linux administration;<br/>
                - root access;<br/>
                - SSL certificate and key;<br/>
                - MySQL database;<br/>
                When you click on Setup button, the config file will be generated and you will get instructions on how to finalize your installation.
            </p>
            <hr>
            <?php if ($success) { ?>
                <div id="success" class="alert alert-success col-sm-10">
                    <?php echo $success; ?>
                </div>
            <?php } ?>
            <?php if ($divErrors) { ?>
                <div id="errors" class="alert alert-danger col-sm-10">
                    <?php echo $divErrors; ?>
                </div>
            <?php } ?>
            <form method="post">
                <div class="form-group row">
                    <label for="filenameCert" class="col-sm-3 col-form-label">Certificate path</label>

                    <div class="col-sm-8">
                        <input type="input" class="form-control" name="filenameCert" id="filenameCert" value="<?php echo @$_POST['filenameCert'] ?>" placeholder="Certificate absolute path" required>
                    </div>
                </div>
                <div class="form-group row">
                    <label for="filenameKey" class="col-sm-3 col-form-label">Key path</label>

                    <div class="col-sm-8">
                        <input type="input" class="form-control" name="filenameKey" id="filenameKey" value="<?php echo @$_POST['filenameKey'] ?>" placeholder="Key absolute path" required>
                    </div>
                </div>
                <div class="form-group row">
                    <small>Absolute paths where your certificate and key are. <br/>
                        Contact your host support if you do not know these locations.
                    </small>
                </div>
                <div class="form-group row">
                    <label for="database" class="col-sm-3 col-form-label">Database</label>
                    <div class="col-sm-8">
                        <input type="input" class="form-control" name="database" id="database" placeholder="Database name" value="<?php echo @$_POST['database'] ?>" required>
                    </div>
                </div>
                <div class="form-group row">
                    <label for="username" class="col-sm-3 col-form-label">Database Username</label>
                    <div class="col-sm-8">
                        <input type="input" class="form-control" name="username" id="username" placeholder="Database username" value="<?php echo @$_POST['username'] ?>" required>
                    </div>
                </div>
                <div class="form-group row">
                    <label for="password" class="col-sm-3 col-form-label">Database Password</label>
                    <div class="col-sm-8">
                        <input type="password" class="form-control" name="password" id="password" placeholder="Database password" required>
                    </div>
                </div>
                <div class="form-group row">
                    <small>You need to provide here your database information, where you need your instance to be installed.
                    </small>
                </div>
                <hr>
                <div class="form-group row">
                    <label for="apisecret" class="col-sm-3 col-form-label">API secret key</label>
                    <div class="col-sm-8">
                        <input type="input" class="form-control" name="apisecret" id="apisecret" placeholder="API Secret Key" value="<?php echo @$_POST['apisecret'] ?>" required>
                    </div>
                </div>
                <div class="form-group row">
                    <small>API secret key. You can generate random string from <a href="https://random.org/strings" target="_blank">here</a>
                    </small>
                </div>
                <hr>
                <div class="form-group row">
                    <label for="apisecret" class="col-sm-3 col-form-label">ChatGPT API Key</label>
                    <div class="col-sm-8">
                        <input type="input" class="form-control" name="chatgpt" id="chatgpt" placeholder="ChatGPT API Key" value="<?php echo @$_POST['chatgpt'] ?>">
                    </div>
                </div>
                <div class="form-group row">
                    <small>Steps to get the key: 1. Go to <a href="https://platform.openai.com/" target="_blank">https://platform.openai.com/</a>; 2. Create your account; 3. Generate your <a href="https://platform.openai.com/account/api-keys" target="_blank">APIKey</a>;
                    </small>
                </div>
                <hr>
                <div class="form-group row">
                    <label for="apisecret" class="col-sm-3 col-form-label">HeyGen Video Avatar API Key</label>
                    <div class="col-sm-8">
                        <input type="input" class="form-control" name="videoApi" id="videoApi" placeholder="HeyGen API Key" value="<?php echo @$_POST['videoApi'] ?>">
                    </div>
                </div>
                <div class="form-group row">
                    <small>Steps to get the key: 1. Go to <a href="https://heygen.com/" target="_blank">https://heygen.com/</a>; 2. Create your account; 3. Go to <a href="https://app.heygen.com/settings?nav=API" target="_blank">API</a>;
                    </small>
                </div>
                <div class="form-group row">
                    <label for="apisecret" class="col-sm-3 col-form-label">D-ID Video Avatar API Key</label>
                    <div class="col-sm-8">
                        <input type="input" class="form-control" name="apiKeyDid" id="apiKeyDid" placeholder="D-ID API Key" value="<?php echo checkPost('apiKeyDid') ?>">
                    </div>
                </div>
                <div class="form-group row">
                    <small>Steps to get the key: 1. Go to <a href="https://studio.d-id.com/" target="_blank">https://studio.d-id.com/</a>; 2. Create your account and use trial token or upgrade your <a href="https://www.d-id.com/pricing/api?from=studio_settings" target="_blank">plan</a>; 3. Go to <a href="https://studio.d-id.com/account-settings" target="_blank">API</a> and generate your token;
                    </small>
                </div>
                <hr>

                <div class="form-group row">
                    <label for="apisecret" class="col-sm-3 col-form-label">ElevenLabs API Key (for audio only avatar)</label>
                    <div class="col-sm-8">
                        <input type="input" class="form-control" name="audioApi" id="audioApi" placeholder="ElevenLabs API Key" value="<?php echo checkPost('audioApi') ?>">
                    </div>
                </div>
                <div class="form-group row">
                    <small>Steps to get the key: 1. Go to <a href="https://try.elevenlabs.io/n3s0gi58vq7u" target="_blank">https://elevenlabs.io/</a>; 2. Create your account; 3. Go to <a href="https://elevenlabs.io/app/settings/api-keys" target="_blank">API</a>; 4. Create an API;
                    </small>
                </div>
                <hr>
                <div class="form-group row">
                    <label for="apisecret" class="col-sm-3 col-form-label">OpenRouter.ai API token (for not filtered chat)</label>
                    <div class="col-sm-8">
                        <input type="input" class="form-control" name="apiKeyOpenrouter" id="apiKeyOpenrouter" placeholder="OpenRouter.si API Key" value="<?php echo checkPost('apiKeyOpenrouter') ?>">
                    </div>
                </div>
                <div class="form-group row">
                    <small>Steps to get the key: 1. Go to <a href="https://openrouter.ai/" target="_blank">https://openrouter.ai/</a>; 2. Create your account; 3. Go to Settings -> <a href="https://openrouter.ai/settings/keys" target="_blank">API Keys</a>, create an API key and copy it.;
                    </small>
                </div>
                <hr>
                <div class="form-group row">
                    <label for="apisecret" class="col-sm-3 col-form-label">Anakin.ai API token (for not filtered chat)</label>
                    <div class="col-sm-8">
                        <input type="input" class="form-control" name="apiKeyAnakin" id="apiKeyAnakin" placeholder="Anakin.si API Key" value="<?php echo checkPost('apiKeyAnakin') ?>">
                    </div>
                </div>
                <div class="form-group row">
                    <small>Steps to get the key: 1. Go to <a href="https://anakin.ai/?r=FgqIm0ai" target="_blank">https://anakin.ai/?r=FgqIm0ai/</a>; 2. Create your account; 3. Add a subscription plan; 4. Go to API Access Token, create and copy it. You can get more information from the <a href="https://anakin.ai/docs/app-integration/api-integration" target="_blank">documentation page</a>;
                    </small>
                </div>
                <hr>

                <div class="form-group row">
                    <div class="col-sm-10 offset-sm-2">
                        <button type="submit" class="btn btn-primary">Setup</button>
                    </div>
                </div>

            </form>
        </div>
    </body>
</html>