#!/bin/bash
# Weekly backup script - run locally or via cron
# Backs up: database from server + local code
# Keeps last 5 backups

BACKUP_BASE="$HOME/Hera DOCS/Projects/Essential Oil Formula Cost Calculator/backups"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="$BACKUP_BASE/$DATE"

mkdir -p "$BACKUP_DIR"

echo "📦 Backing up to: $BACKUP_DIR"

# 1. Download database from server
echo "  Downloading database..."
ssh fam@oci.euphon.net "kubectl exec -n oil-calculator deploy/oil-calculator -- cat /data/oil_calculator.db" > "$BACKUP_DIR/oil_calculator.db" 2>/dev/null

if [ $? -eq 0 ] && [ -s "$BACKUP_DIR/oil_calculator.db" ]; then
  echo "  ✅ Database: $(du -h "$BACKUP_DIR/oil_calculator.db" | cut -f1)"
else
  echo "  ❌ Database download failed"
fi

# 2. Copy local code
echo "  Copying code..."
PROJECT="$HOME/Hera DOCS/Projects/Essential Oil Formula Cost Calculator"
cp -r "$PROJECT/backend" "$BACKUP_DIR/"
cp -r "$PROJECT/frontend" "$BACKUP_DIR/"
cp "$PROJECT/Dockerfile" "$BACKUP_DIR/"
echo "  ✅ Code copied"

# 3. Export all data as JSON (recipes, oils, users)
echo "  Exporting data..."
ADMIN_TOKEN=$(cat /tmp/oil_admin_token.txt 2>/dev/null)
if [ -n "$ADMIN_TOKEN" ]; then
  curl -s -H "Authorization: Bearer $ADMIN_TOKEN" https://oil.oci.euphon.net/api/recipes > "$BACKUP_DIR/recipes.json" 2>/dev/null
  curl -s -H "Authorization: Bearer $ADMIN_TOKEN" https://oil.oci.euphon.net/api/oils > "$BACKUP_DIR/oils.json" 2>/dev/null
  curl -s -H "Authorization: Bearer $ADMIN_TOKEN" https://oil.oci.euphon.net/api/tags > "$BACKUP_DIR/tags.json" 2>/dev/null
  curl -s -H "Authorization: Bearer $ADMIN_TOKEN" https://oil.oci.euphon.net/api/users > "$BACKUP_DIR/users.json" 2>/dev/null
  echo "  ✅ Data exported"
else
  echo "  ⚠️ No admin token, skipping data export"
fi

# 4. Keep only last 5 backups
echo "  Cleaning old backups..."
ls -dt "$BACKUP_BASE"/*/ 2>/dev/null | tail -n +31 | xargs rm -rf 2>/dev/null
REMAINING=$(ls -d "$BACKUP_BASE"/*/ 2>/dev/null | wc -l)
echo "  ✅ $REMAINING backups retained"

echo ""
echo "✅ Backup complete: $BACKUP_DIR"
ls -la "$BACKUP_DIR/"
