import paramiko

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)

r("""
cat << 'EOF' > /var/www/iam/drizzle/db.ts
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema';

const connectionString = process.env.DATABASE_URL as string;

// Connection Pool Global Cache for Next.js App Router
declare global {
  var _postgresClient: postgres.Sql | undefined;
}

const queryClient = global._postgresClient || postgres(connectionString, { max: 10 });

if (process.env.NODE_ENV !== 'production') {
  global._postgresClient = queryClient;
}

export const db = drizzle(queryClient, { schema });
EOF

cd /var/www/iam && npm run build && pm2 restart iam
""")

c.close()
