#define _GNU_SOURCE
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    // 1. Ensure PATH has standard system administrative and binary paths
    setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);

    // 2. Elevate to root privileges
    if (setuid(0) != 0) {
        perror("setuid");
    }
    if (setgid(0) != 0) {
        perror("setgid");
    }

    // 3. Handle termination flags (--kill, -k, --disconnect, --stop)
    if (argc > 1 && (strcmp(argv[1], "--kill") == 0 ||
                     strcmp(argv[1], "-k") == 0 ||
                     strcmp(argv[1], "--disconnect") == 0 ||
                     strcmp(argv[1], "--stop") == 0)) {
        // Force kill all client engine processes
        system("killall -9 rezerv_client >/dev/null 2>&1");
        system("pkill -9 -f /opt/rezerv-vpn/rezerv_client >/dev/null 2>&1");
        system("pkill -9 -x rezerv_client >/dev/null 2>&1");

        // Clean up tun0 interface and system DNS/IPv6 routing
        system("ip link delete tun0 >/dev/null 2>&1");
        system("sysctl -w net.ipv6.conf.all.disable_ipv6=0 >/dev/null 2>&1");
        system("resolvectl revert tun0 >/dev/null 2>&1");
        system("resolvectl flush-caches >/dev/null 2>&1");
        return 0;
    }

    // 4. Before starting a new connection: clean up any stale previous instances
    system("killall -9 rezerv_client >/dev/null 2>&1");
    system("pkill -9 -x rezerv_client >/dev/null 2>&1");
    system("ip link delete tun0 >/dev/null 2>&1");

    // 5. Optimize network stack (disable IPv6 delay for peak throughput)
    system("sysctl -w net.ipv6.conf.all.disable_ipv6=1 >/dev/null 2>&1");

    // 6. Run core VPN client engine
    execv("/opt/rezerv-vpn/rezerv_client", argv);
    perror("execv(/opt/rezerv-vpn/rezerv_client)");
    return 1;
}
