#!/usr/bin/env python3
"""
Release cPanel Passenger app lock for phingrazuri.
Run on the server: python release_lock.py
"""
import os
import sys
import glob
import signal
import subprocess

APP_NAME = "phingrazuri"
HOME = os.path.expanduser("~")

print(f"\n{'='*55}")
print(f"  Passenger Lock Releaser — {APP_NAME}")
print(f"{'='*55}\n")

# ── 1. Find and remove lock files ─────────────────────────────
lock_patterns = [
    f"{HOME}/.cpanel/passenger/{APP_NAME}.lock",
    f"{HOME}/.cpanel/passenger/{APP_NAME}*.lock",
    f"/var/cpanel/passenger/apps/{APP_NAME}.lock",
    f"{HOME}/phingrazuri/tmp/restart.txt",
    f"{HOME}/phingrazuri/tmp/*.lock",
    f"{HOME}/phingrazuri/*.lock",
]

found_any = False
for pattern in lock_patterns:
    for path in glob.glob(pattern):
        try:
            os.remove(path)
            print(f"  REMOVED lock file: {path}")
            found_any = True
        except Exception as e:
            print(f"  FAILED to remove {path}: {e}")

if not found_any:
    print("  No lock files found in standard locations")

# ── 2. Kill any stale Passenger / Python processes for this app ─
print("\n  Checking for stale processes...")
try:
    result = subprocess.run(
        ["ps", "aux"],
        capture_output=True, text=True
    )
    lines = result.stdout.splitlines()
    killed = 0
    current_pid = os.getpid()

    for line in lines:
        if APP_NAME in line and "release_lock" not in line:
            parts = line.split()
            if len(parts) > 1:
                try:
                    pid = int(parts[1])
                    if pid == current_pid:
                        continue  # don't kill ourselves
                    os.kill(pid, signal.SIGTERM)
                    print(f"  KILLED PID {pid}: {' '.join(parts[10:])[:60]}")
                    killed += 1
                except (ValueError, ProcessLookupError, PermissionError) as e:
                    print(f"  Could not kill PID {parts[1]}: {e}")

    if killed == 0:
        print("  No stale processes found")
    else:
        print(f"  Killed {killed} stale process(es)")

except Exception as e:
    print(f"  Could not check processes: {e}")

# ── 3. Touch tmp/restart.txt to force Passenger restart ────────
restart_paths = [
    f"{HOME}/phingrazuri/tmp/restart.txt",
    f"{HOME}/phingrazuri/restart.txt",
]
print("\n  Triggering Passenger restart...")
for path in restart_paths:
    try:
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, 'w') as f:
            import datetime
            f.write(str(datetime.datetime.now()))
        print(f"  CREATED: {path}")
        break
    except Exception as e:
        print(f"  Could not create {path}: {e}")

# ── 4. Try cPanel API restart if available ─────────────────────
print("\n  Attempting cPanel app restart via CLI...")
restart_cmds = [
    f"passenger-config restart-app {HOME}/phingrazuri",
    f"uapi ApplicationManager restart_app name={APP_NAME}",
]
for cmd in restart_cmds:
    try:
        result = subprocess.run(
            cmd, shell=True, capture_output=True, text=True, timeout=15
        )
        if result.returncode == 0:
            print(f"  OK: {cmd}")
            break
        else:
            print(f"  FAILED: {cmd}\n    {result.stderr.strip()[:100]}")
    except Exception as e:
        print(f"  Could not run: {cmd} — {e}")

print(f"\n{'='*55}")
print("  Done. Now:")
print("  1. Go to cPanel → Python Apps → phingrazuri → Restart")
print("  2. Or wait 30 seconds for Passenger to auto-restart")
print("  3. Then run: python run_migrations.py")
print(f"{'='*55}\n")
