import os
import sys
import time
import signal
from subprocess import Popen, PIPE, DEVNULL

APP_DIR = '/root/Flask'
APP_FILE = 'manage.py runserver'
PID_FILE = '/var/run/Flask_app.pid'

def start_app():
    command = f'cd {APP_DIR} &&  python3.8 {APP_FILE}'
    process = Popen(command, shell=True, stdout=DEVNULL, stderr=DEVNULL, preexec_fn=os.setsid)
    with open(PID_FILE, 'w') as pid_file:
        pid_file.write(str(process.pid))

def stop_app():
    if os.path.exists(PID_FILE):
        with open(PID_FILE, 'r') as pid_file:
            pid = int(pid_file.read().strip())
            os.killpg(pid, signal.SIGTERM)
        os.remove(PID_FILE)

def restart_app():
    stop_app()
    time.sleep(1)
    start_app()

def status_app():
    if os.path.exists(PID_FILE):
        with open(PID_FILE, 'r') as pid_file:
            pid = int(pid_file.read().strip())
            try:
                os.kill(pid, 0)
                return f"Your app is running (PID: {pid})"
            except ProcessLookupError:
                return "Your Flask app is not running"
    else:
        return "Your Flask  app is not running"

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print("Usage: python3.8 your_app_service.py [start|stop|restart|status]")
        sys.exit(1)

    action = sys.argv[1]

    if action == 'start':
        start_app()
        print("Your Flask app has been started.")
    elif action == 'stop':
        stop_app()
        print("Your Flask app has been stopped.")
    elif action == 'restart':
        restart_app()
        print("Your Flask app has been restarted.")
    elif action == 'status':
        status = status_app()
        print(status)    
    else:
        print("Invalid action. Usage: python3 your_app_service.py [start|stop|restart|status]")
        sys.exit(1)