<?php
function validateAndFollowUrl($url) {
    $output = [];
    $returnVal = 0;
    
    exec('/usr/bin/python3 fixurl.py ' . escapeshellarg($url) . ' ' . escapeshellarg($ip), $output, $returnVal);
    
    if ($returnVal !== 0) {
        return ['error' => 'URL validation failed'];
    }
    
    $result = json_decode($output[0], true);
    
    if (!$result['success']) {
        return ['error' => $result['error']];
    }
    
    return $result;
}

function validateDomain($domain) {
    return filter_var($domain, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME);
}

function validateIP($ip) {
    return filter_var($ip, FILTER_VALIDATE_IP);
}

function testConfig($configPath) {
    exec('sudo /usr/local/bin/angie-tempurl test 2>&1', $output, $testStatus);
    error_log("Angie config test output: " . implode("\n", $output));
    
    if ($testStatus !== 0) {
        if (file_exists($configPath)) {
            unlink($configPath);
        }
        error_log("Angie config test failed for $configPath");
        return false;
    }
    return true;
}

function reloadAngie() {
    exec('sudo /usr/local/bin/angie-tempurl reload 2>&1', $output, $reloadStatus);
    error_log("Angie reload output: " . implode("\n", $output));
    
    if ($reloadStatus !== 0) {
        error_log("Angie reload failed");
        return false;
    }
    return true;
}

function checkRateLimit($ip, $limit = 10, $period = 600) {
    $rateFile = sys_get_temp_dir() . "/ratelimit_" . md5($ip);
    
    if (file_exists($rateFile)) {
        $data = json_decode(file_get_contents($rateFile), true);
        if (time() - $data['start'] > $period) {
            $data = ['count' => 1, 'start' => time()];
        } else if ($data['count'] >= $limit) {
            return false;
        } else {
            $data['count']++;
        }
    } else {
        $data = ['count' => 1, 'start' => time()];
    }
    
    file_put_contents($rateFile, json_encode($data));
    return true;
}

$domain = $_POST['domain'] ?? $_GET['domain'] ?? '';
$ip = $_POST['ip'] ?? $_GET['ip'] ?? '';
$response = '';

if (!empty($domain) && !empty($ip)) {
    if (!checkRateLimit($_SERVER['REMOTE_ADDR'])) {
        $response = "Rate limit exceeded. Please try again later.";
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            echo $response;
            exit;
        }
    }
    
    if (validateDomain($domain) && validateIP($ip)) {
        $urlResponse = validateAndFollowUrl($domain);
        if (isset($urlResponse['error'])) {
            $response = "URL error: " . $urlResponse['error'];
        } else {
            $finalDomain = $urlResponse['final_domain'];
            $tempUrl = $urlResponse['temp_url'];
            $needsSpecialHandling = $urlResponse['needs_special_handling'] ?? false;

            if ($needsSpecialHandling) {
                $configTemplate = <<<CONFIG
server {
    listen 443 ssl;
    server_name {$tempUrl};

    ssl_certificate /home/nginx/ssl/angie.crt;
    ssl_certificate_key /home/nginx/ssl/angie.key;

    large_client_header_buffers 4 32k;
    client_header_buffer_size 16k;
    proxy_buffer_size 16k;
    proxy_buffers 8 16k;
    proxy_busy_buffers_size 32k;

    location / {
        add_header X-Robots-Tag "noindex, nofollow";
        proxy_pass http://{$ip};
        proxy_buffering on;
        proxy_buffers 16 4k;
        proxy_set_header Host {$finalDomain};
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Forwarded-Port 443;
        proxy_set_header X-Forwarded-Ssl on;
        proxy_ssl_verify off;
        proxy_ssl_server_name on;
        proxy_set_header Accept-Encoding "";
        proxy_redirect ~^http://(.*)$ https://{$tempUrl};
        proxy_redirect ~^https://(.*)$ https://{$tempUrl};
    }
    
    sub_filter '{$finalDomain}' '{$tempUrl}';
    sub_filter_once off;
    sub_filter_types *;
}
CONFIG;
            } else {
                $configTemplate = <<<CONFIG
server {
    listen 443 ssl;
    server_name {$tempUrl};

    ssl_certificate /home/nginx/ssl/angie.crt;
    ssl_certificate_key /home/nginx/ssl/angie.key;

    large_client_header_buffers 4 32k;
    client_header_buffer_size 16k;
    proxy_buffer_size 16k;
    proxy_buffers 8 16k;
    proxy_busy_buffers_size 32k;

    location / {
        add_header X-Robots-Tag "noindex, nofollow";
        proxy_pass https://{$ip};
        proxy_buffering on;
        proxy_buffers 16 4k;
        proxy_set_header Host {$finalDomain};
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_ssl_verify off;
        proxy_ssl_server_name on;
        proxy_set_header Accept-Encoding "";
        proxy_redirect https://{$finalDomain} https://{$tempUrl};
    }
    
    sub_filter '{$finalDomain}' '{$tempUrl}';
    sub_filter_once off;
    sub_filter_types *;
}
CONFIG;
            }

            $configPath = "/home/nginx/tempurl/{$tempUrl}.conf";

            if (file_put_contents($configPath, $configTemplate) === false) {
                $response = "Failed to write configuration file.";
            } else {
                if (!testConfig($configPath)) {
                    $response = "No. Try again.";
                } else {
                    if (!reloadAngie()) {
                        unlink($configPath);
                        $response = "Failed to reload Angie configuration.";
                    } else {
                        if ($_SERVER['REQUEST_METHOD'] === 'GET' && !empty($_GET['domain']) && !empty($_GET['ip'])) {
                            if (strpos($_SERVER['HTTP_USER_AGENT'], 'curl') !== false) {
                                echo "https://{$tempUrl}\n";
                                exit;
                            } else {
                                header("Location: https://{$tempUrl}");
                                exit;
                            }
                        }
                        $response = "<a href='https://{$tempUrl}' target='_blank'>https://{$tempUrl}</a>";
                    }
                }
            }
        }
    } else {
        $response = "Invalid domain or IP. Please provide a valid domain and IP address.";
    }
} else if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $response = "Please provide both domain and IP address.";
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    echo $response;
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Create a temporary URL</title>
    <meta name="description" content="Create a temporary URL with tempurl.cc for easy DNS testing. Simplify your web development and troubleshooting with fast and secure temporary URLs.">
    <link rel="icon" type="image/x-icon" href="favicon.png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
        }

        .container {
            background-color: #fff;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            text-align: center;
            max-width: 500px;
            margin: 50px auto 10px;
        }

        h1 {
            color: #3d67ff;
            margin-bottom: 20px;
        }

        form {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        input[type="text"],
        input[type="submit"] {
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            border: 1px solid #ccc;
            font-size: 16px;
            width: 100%;
            max-width: 300px;
        }

        input[type="submit"] {
            background-color: #3d67ff;
            color: #fff;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        input[type="submit"]:hover {
            background-color: #555;
        }

        #loading {
            display: none;
            margin-top: 20px;
            font-weight: bold;
            color: #333;
        }

        #output {
            margin-top: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        #output a {
            color: #3d67ff;
            text-decoration: none;
            margin-right: 10px;
        }

        #copyIcon {
            cursor: pointer;
            width: 20px;
            height: 20px;
        }

        .note {
            color: #555;
            font-size: 14px;
            margin-top: 0px;
            text-align: center;
        }

        .warning-text {
            color: #cccccc;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Create Temp URL</h1>
        <form id="tempUrlForm">
            <input type="text" id="domain" name="domain" placeholder="domain.com" required>
            <input type="text" id="ip" name="ip" placeholder="Server IP" required>
            <input type="submit" value="Create">
        </form>
        <div id="loading">Doin' Math... Please wait.<br><img src="loading.gif"></div>
        <div id="output"><?php echo $response; ?></div>
    </div>
    <div class="note">All temporary links expire after 72 hours.<br><span class="warning-text">This service is provided free and as as result, no abuse will be tolerated. &#10084;  -Les</span></div>

    <script>
        function showLoading() {
            document.getElementById('loading').style.display = 'block';
            document.getElementById('output').innerHTML = '';
        }

        function handleFormSubmit(event) {
            event.preventDefault();
            showLoading();

            const formData = new FormData(event.target);

            fetch('/', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                document.getElementById('loading').style.display = 'none';
                const outputDiv = document.getElementById('output');
                outputDiv.innerHTML = `${data}<i id="copyIcon" class="fa-solid fa-clipboard" title="Copy URL" onclick="copyToClipboard()" style="color: #3d67ff;"></i>`;
                
                document.getElementById('tempUrlForm').querySelector('input[type="submit"]').disabled = true;
                setTimeout(() => {
                    document.getElementById('tempUrlForm').querySelector('input[type="submit"]').disabled = false;
                }, 10000);
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('loading').style.display = 'none';
                document.getElementById('output').innerHTML = `<span class="error-text">An error occurred: ${error.message}</span>`;
            });
        }

        function copyToClipboard() {
            const url = document.getElementById('output').querySelector('a').href;
            navigator.clipboard.writeText(url)
                .then(() => {
                    const checkmarkIcon = document.createElement('i');
                    checkmarkIcon.classList.add('fa-solid', 'fa-check');
                    checkmarkIcon.style.color = '#008000';
                    document.getElementById('copyIcon').replaceWith(checkmarkIcon);
                })
                .catch(error => {
                    console.error('Failed to copy URL:', error);
                });
        }

        document.getElementById('tempUrlForm').addEventListener('submit', handleFormSubmit);
    </script>
</body>
</html>