import time
import subprocess
import os

script_time_gap = 15
screen_name = 'kr_temp_server'
script_name = 'kr_temporary_server.py'
# script_args = '1134 staging'
last_run_file = "/var/www/html/ovpn/vpnGate/kr_temporary_last_run.txt"

def get_last_run_time():
    try:
        with open(last_run_file, "r") as f:
            return int(f.read().strip())
    except Exception as e:
        print(f"Error reading last run time: {e}")
        return 0
def check_process_in_screen(script_name):
    try:
        result = subprocess.run(['pgrep', '-f', f"{script_name}"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        return result.stdout.strip() != ''
    except Exception as e:
        print(f"Error checking process: {e}")
        return False

def update_last_run_time():
    try:
        with open(last_run_file, "w") as f:
            f.write(str(int(time.time())))
    except Exception as e:
        print(f"Error updating last run time: {e}")

def check_and_run_vpn():
    current_time = int(time.time())
    last_run_time = get_last_run_time()

    time_diff = current_time - last_run_time
    is_running = check_process_in_screen(script_name)

    if not is_running:
        print('Script is not running')
        if time_diff >= script_time_gap * 60:
            print(f"VPN hasn't been run for {time_diff // 60} minutes, running now.")

            screen_exists = subprocess.run(
                ["screen", "-list"],
                capture_output=True, text=True
            ).stdout
            if screen_name not in screen_exists:
                subprocess.run(["screen", "-dmS", screen_name])
                print(f"Created a new screen session named {screen_name}.")
            
            subprocess.run(
                ["screen", "-S", screen_name, "-p", "0", "-X", "stuff", f'/usr/bin/python3 /var/www/html/ovpn/vpnGate/{script_name}\n']
            )
            update_last_run_time()
        else:
            print(f"VPN has been run recently, skipping. ({time_diff // 60} minutes ago)")
    else:
        print('Script is running')


if __name__ == "__main__":
    check_and_run_vpn()
