#!/bin/bash
# =============================================
# pull-backup.sh — Run on VM (local machine)
# Pulls a backup from /backups/main-server/ 
# and extracts it ready for restore.
#
# Usage:
#   ./pull-backup.sh                          → list available backups
#   ./pull-backup.sh latest                   → pull the most recent backup
#   ./pull-backup.sh myapps-backup-20260311_021129.tar.gz  → pull specific one
# =============================================

BACKUP_DIR="/backups/main-server"
RESTORE_DIR="/root/restored-backups"

mkdir -p "$RESTORE_DIR"

echo "========================================="
echo "📥 Backup Pull Tool"
echo "   Source:  $BACKUP_DIR"
echo "   Dest:    $RESTORE_DIR"
echo "========================================="

# --------------------------------------------------
# No argument → list available backups
# --------------------------------------------------
if [ -z "${1:-}" ]; then
    echo ""
    echo "📋 Available backups:"
    echo ""
    if ls "$BACKUP_DIR"/myapps-backup-*.tar.gz &>/dev/null; then
        ls -lht "$BACKUP_DIR"/myapps-backup-*.tar.gz | awk '{print NR". "$NF" ("$5")"}'
    else
        echo "   (no backups found in $BACKUP_DIR)"
    fi
    echo ""
    echo "Usage:"
    echo "  $0 latest"
    echo "  $0 myapps-backup-20260311_021129.tar.gz"
    exit 0
fi

# --------------------------------------------------
# 'latest' → pick newest file
# --------------------------------------------------
if [ "$1" = "latest" ]; then
    BACKUP_FILE=$(ls -t "$BACKUP_DIR"/myapps-backup-*.tar.gz 2>/dev/null | head -1)
    if [ -z "$BACKUP_FILE" ]; then
        echo "❌ No backups found in $BACKUP_DIR"
        exit 1
    fi
    echo "🕐 Latest backup: $(basename $BACKUP_FILE)"
else
    # Specific filename given — accept with or without path prefix
    BASENAME=$(basename "$1")
    BACKUP_FILE="$BACKUP_DIR/$BASENAME"
    if [ ! -f "$BACKUP_FILE" ]; then
        echo "❌ Not found: $BACKUP_FILE"
        echo "   Run $0 with no arguments to list available backups."
        exit 1
    fi
fi

BACKUP_NAME=$(basename "$BACKUP_FILE" .tar.gz)
EXTRACT_PATH="$RESTORE_DIR/$BACKUP_NAME"

# --------------------------------------------------
# Already extracted?
# --------------------------------------------------
if [ -d "$EXTRACT_PATH" ]; then
    echo ""
    echo "⚠️  This backup is already extracted at:"
    echo "   $EXTRACT_PATH"
    echo ""
    read -p "   Re-extract? (y/N): " CONFIRM
    if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then
        echo "   Skipping extraction."
    else
        rm -rf "$EXTRACT_PATH"
        echo "   🗑️  Removed old extraction."
    fi
fi

BACKUP_SIZE=$(du -h "$BACKUP_FILE" | cut -f1)
echo ""
echo "📦 Extracting: $(basename $BACKUP_FILE)  [$BACKUP_SIZE]"
echo "   → $EXTRACT_PATH"
echo ""

cd "$RESTORE_DIR"
tar -xzf "$BACKUP_FILE"

if [ $? -ne 0 ]; then
    echo "❌ Extraction failed!"
    exit 1
fi

echo ""
echo "✅ Extraction complete!"
echo ""
echo "📋 Backup contents:"
ls -lh "$EXTRACT_PATH/"
echo ""
echo "========================================="
echo "🚀 To restore this backup:"
echo ""
echo "  # On THIS VM (local restore):"
echo "  cd $EXTRACT_PATH"
echo "  ./restore-myapps.sh"
echo ""
echo "  # On the MAIN SERVER (remote restore via SSH):"
echo "  cd $EXTRACT_PATH"
echo "  ./restore-myapps.sh --remote <SERVER_IP> <SSH_USER> [SSH_KEY or PASSWORD]"
echo "========================================="
