import paramiko
import os

c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect('160.187.143.253', username='root', password=';ur7n)LC1BQ;')

def r(cmd):
    print(f"Executing: {cmd}")
    try:
        _, so, se = c.exec_command(cmd, timeout=30)
        stdout = so.read().decode('utf-8', 'replace').strip()
        stderr = se.read().decode('utf-8', 'replace').strip()
        if stdout: print(f"STDOUT:\n{stdout}")
        if stderr: print(f"STDERR:\n{stderr}")
        return stdout
    except Exception as e: 
        return str(e)

with open(r'C:\x\workspace\jumpa.id\iam\drizzle\db.ts', 'r') as f:
    db_ts_content = f.read()

# Escape single quotes and backslashes for bash
db_ts_content_escaped = db_ts_content.replace('\\', '\\\\').replace("'", "'\\''")

r(f"echo '{db_ts_content_escaped}' > /var/www/iam/drizzle/db.ts")

# Rebuild is required since Next.js compiles the API routes into .next
r("cd /var/www/iam && npm run build")
r("pm2 restart supreme-iam")

c.close()
