import paramiko, sys

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect("65.75.210.95", username="root", password="%8qd6oJx%PBB", timeout=30)

ENV = """DATABASE_HOST=127.0.0.1
DATABASE_PORT=3306
DATABASE_USER=u4_eUOr0KnLCF
DATABASE_PASSWORD=+Q8@WPMQbr+@3vhfKJEM!4A2
DATABASE_NAME=s4_Urban
NODE_ENV=production
NEXTAUTH_URL=https://urbangamers.es
NEXTAUTH_SECRET=9c24404c2ca1a81e85f7f076485c1c49
NEXT_PUBLIC_DISCORD_CLIENT_ID=1276672022725791764
NEXT_PUBLIC_DISCORD_REDIRECT_URI=https://urbangamers.es/api/auth/discord/callback
NEXT_PUBLIC_BASE_URL=https://urbangamers.es
DISCORD_CLIENT_SECRET=HiX-3FsawXQ5_Rjx1RTiId1-DVP4obst
DISCORD_BOT_TOKEN=MTI3NjY3MjAyMjcyNTc5MTc2NA.GYerC5.jEn7PX3sGM9c1Bt3IUEmQsMmPuLPheFaFtiWgI
JWT_SECRET=0da2177fed87b45587e835b0ec78438b
MTA_SERVER_IP=65.75.210.95
MTA_SERVER_PORT=8888
SITE_URL=https://urbangamers.es
BASE_URL=https://urbangamers.es
PORT=3000
"""

cmds = [
    f"rm -f /var/www/servidor/web/.env.production.local /var/www/servidor/web/.env.development.local",
]

sftp = client.open_sftp()
with sftp.file("/var/www/servidor/web/.env.production", "w") as f:
    f.write(ENV)
sftp.close()

for cmd in cmds + [
    "cd /var/www/servidor/web && pm2 restart urbangamers --update-env",
    "sleep 2",
    "curl -s -X POST http://127.0.0.1:3000/api/auth/login -H 'Content-Type: application/json' -d '{\"username\":\"navin\",\"password\":\"wrongpass\"}'",
]:
    print(">>>", cmd[:80])
    _, o, _ = client.exec_command(cmd, get_pty=True)
    out = o.read().decode("utf-8", errors="replace")
    sys.stdout.buffer.write(out.encode("utf-8", errors="replace"))

client.close()
