#!/bin/bash
# ============================================================
# Instrument Cluster — Phase 2 SSH Commands
# Run AFTER Phase 1 is confirmed complete
# ============================================================

# ── BLOCK 1: Run database schema ──────────────────────────
# Upload schema.sql to /home/ic-api/ first, then:
cd /home/ic-api
mysql -u ic_user -p ic_production < schema.sql
# Verify tables:
mysql -u ic_user -p ic_production -e "SHOW TABLES;"
# Should show: audit_log, sessions, subscriptions, users

# ── BLOCK 2: Install Node dependencies ────────────────────
cd /home/ic-api
npm install
# Should see: added N packages

# ── BLOCK 3: Generate JWT secret ──────────────────────────
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
# Copy this output — paste it as JWT_SECRET in .env

# ── BLOCK 4: Create .env file ─────────────────────────────
# Upload env.template to /home/ic-api/.env
# Then fill in the values:
#   - JWT_SECRET     = output from Block 3 above
#   - DB_PASS        = password you set in Phase 1 Block 6
#   - STRIPE_*       = from Stripe dashboard (you paste these)
#   - SMTP_PASS      = cPanel email password for noreply@instrumentcluster.io
chmod 600 /home/ic-api/.env   # restrict to root only

# ── BLOCK 5: Start API server with PM2 ────────────────────
cd /home/ic-api
pm2 start server.js --name ic-api --node-args="--max-old-space-size=256"
pm2 save

# Set PM2 to start on reboot:
pm2 startup systemd
# PM2 will print a command — copy and run it

# ── BLOCK 6: Verify server is running ─────────────────────
pm2 status
curl -s http://127.0.0.1:3001/api/health
# Should return: {"status":"ok","ts":...,"version":"1.0.0"}

# ── BLOCK 7: Check PM2 logs for errors ────────────────────
pm2 logs ic-api --lines 20

echo "Phase 2 complete — API server running"
