#!/bin/bash
# Post-deploy: backup DB + upload artifacts to storage box
# Run after each successful deploy
set -uo pipefail

VERSION=$(cd /opt/task-team && git describe --tags --always 2>/dev/null || echo "unknown")
DATE=$(date +%Y%m%d_%H%M)
REMOTE="u458763-sub3@u458763.your-storagebox.de"
PORT=23
LOG="/var/log/taskteam-backup.log"

echo "[$(date +%H:%M:%S)] Post-deploy backup starting: $VERSION" | tee -a $LOG

# 1. DB backup
echo "[$(date +%H:%M:%S)] Running DB backup..." | tee -a $LOG
/opt/task-team/backup.sh >> $LOG 2>&1
DB_EXIT=$?

# 2. Upload latest DB backup to storage box
LATEST_BACKUP=$(ls -t /opt/task-team/backups/*.gz 2>/dev/null | head -1)
if [ -f "${LATEST_BACKUP:-}" ]; then
    echo "[$(date +%H:%M:%S)] Uploading DB backup: $(basename $LATEST_BACKUP)" | tee -a $LOG
    scp -P $PORT -o ConnectTimeout=10 -o BatchMode=yes "$LATEST_BACKUP" "$REMOTE:releases/backups/" 2>>$LOG ||         echo "[$(date +%H:%M:%S)] WARN: Storage box upload failed (DB backup saved locally)" | tee -a $LOG
fi

# 3. Upload APK if exists
APK_DIR="/opt/task-team/mobile/dist/android"
APK=$(ls -t $APK_DIR/*.apk 2>/dev/null | head -1)
if [ -f "${APK:-}" ]; then
    echo "[$(date +%H:%M:%S)] Uploading APK: $(basename $APK)" | tee -a $LOG
    scp -P $PORT -o ConnectTimeout=10 -o BatchMode=yes "$APK" "$REMOTE:releases/android/task-team-${VERSION}-${DATE}.apk" 2>>$LOG ||         echo "[$(date +%H:%M:%S)] WARN: Storage box APK upload failed" | tee -a $LOG
fi

# 4. Upload web build if exists
if [ -d "/opt/task-team/web/.next" ]; then
    WEB_ARCHIVE="/tmp/task-team-web-${VERSION}-${DATE}.tar.gz"
    tar czf "$WEB_ARCHIVE" -C /opt/task-team/web .next public package.json next.config.ts 2>/dev/null || true
    if [ -f "$WEB_ARCHIVE" ]; then
        scp -P $PORT -o ConnectTimeout=10 -o BatchMode=yes "$WEB_ARCHIVE" "$REMOTE:releases/web/" 2>>$LOG || true
        rm -f "$WEB_ARCHIVE"
    fi
fi

echo "[$(date +%H:%M:%S)] Post-deploy backup complete: $VERSION (DB exit: $DB_EXIT)" | tee -a $LOG
