#!/bin/bash
# PeerCortex safe deploy script — always backup before restart
# NOTE: this only covers server.js + public/index.html (the main site,
# PM2 process "peercortex"). The Fastify API server (PM2 process
# "peercortex-api", dist/api/index.js, port 3102) needs `npm run build`
# run first and `pm2 restart peercortex-api` separately -- see
# ecosystem.config.js on Erik for both app definitions.
BACKUP_DIR=/opt/peercortex-app/backups
mkdir -p $BACKUP_DIR
TS=$(date +%Y%m%d_%H%M%S)
cp /opt/peercortex-app/server.js $BACKUP_DIR/server.js.$TS
cp /opt/peercortex-app/public/index.html $BACKUP_DIR/index.html.$TS
# Keep only last 20 backups
ls -t $BACKUP_DIR/server.js.* 2>/dev/null | tail -n +21 | xargs rm -f 2>/dev/null
ls -t $BACKUP_DIR/index.html.* 2>/dev/null | tail -n +21 | xargs rm -f 2>/dev/null
echo "[backup] Saved server.js + index.html ($TS)"
pm2 restart peercortex
