#!/bin/bash
# ===================================================================
# TK Factory Services - 백업 스크립트
# ===================================================================
# 사용법: ./scripts/backup.sh [backup_dir]
# ===================================================================

set -e

BACKUP_DIR="${1:-./backups/$(date +%Y%m%d_%H%M%S)}"
mkdir -p "$BACKUP_DIR"

echo "=== TK Factory Services Backup ==="
echo "Backup directory: $BACKUP_DIR"
echo ""

# 1. MariaDB 백업
echo "[1/4] Backing up MariaDB..."
docker exec tk-mariadb mysqldump -u root -p"${MYSQL_ROOT_PASSWORD}" --all-databases \
  > "$BACKUP_DIR/mariadb_all.sql" 2>/dev/null && \
  echo "  MariaDB backup: OK" || echo "  MariaDB backup: SKIPPED (not running)"

# 2. PostgreSQL 백업
echo "[2/4] Backing up PostgreSQL..."
docker exec tk-postgres pg_dump -U "${POSTGRES_USER:-mproject}" "${POSTGRES_DB:-mproject}" \
  > "$BACKUP_DIR/postgres_mproject.sql" 2>/dev/null && \
  echo "  PostgreSQL backup: OK" || echo "  PostgreSQL backup: SKIPPED (not running)"

# 3. Upload 파일 백업
echo "[3/4] Backing up uploads..."
for vol in system1_uploads system2_uploads system3_uploads; do
  if docker volume inspect "tk-factory-services_${vol}" >/dev/null 2>&1; then
    docker run --rm -v "tk-factory-services_${vol}:/data" -v "$(cd "$BACKUP_DIR" && pwd):/backup" \
      alpine tar czf "/backup/${vol}.tar.gz" -C /data . 2>/dev/null && \
      echo "  ${vol}: OK" || echo "  ${vol}: SKIPPED"
  fi
done

# 4. 설정 파일 백업
echo "[4/4] Backing up config files..."
cp -f .env "$BACKUP_DIR/.env.bak" 2>/dev/null || true
cp -f docker-compose.yml "$BACKUP_DIR/docker-compose.yml.bak" 2>/dev/null || true

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