#!/usr/bin/env bash
# Backup staging database to /root/z_crm/backups/ on the server.
# Usage: SSHPASS=yourpassword ./scripts/backup-staging.sh
# Or with SSH keys: ./scripts/backup-staging.sh
#
# Creates backups/backup_YYYYMMDD_HHMMSS.sql on the staging server.

set -e

STAGING_HOST="${STAGING_HOST:-root@37.60.249.71}"
BACKUP_DIR="/root/z_crm/backups"
BACKUP_FILE="backup_$(date +%Y%m%d_%H%M%S).sql"

echo "Backing up staging database..."
echo "Host: $STAGING_HOST"
echo "Target: $BACKUP_DIR/$BACKUP_FILE"
echo ""

CMD="mkdir -p $BACKUP_DIR && cd /root/z_crm && docker compose exec -T postgres pg_dump -U postgres mind14_crm > $BACKUP_DIR/$BACKUP_FILE"

if [ -n "$SSHPASS" ]; then
  sshpass -e ssh -o StrictHostKeyChecking=no "$STAGING_HOST" "$CMD"
else
  ssh -o StrictHostKeyChecking=no "$STAGING_HOST" "$CMD"
fi

echo "Backup complete."
echo "File on server: $BACKUP_DIR/$BACKUP_FILE"
echo "To restore: docker compose exec -T postgres psql -U postgres mind14_crm < $BACKUP_DIR/$BACKUP_FILE"
