#!/bin/bash
# WHP Migration Script: Git-based to Release System
# Migrates existing WHP servers from git-based updates to release system

# Exit on any error
set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Configuration
RELEASE_SERVER="https://whp-releases.cloud-hosting.io"
WHP_DIR="/root/whp"
WEB_DIR="/docker/whp/web"

echo -e "${BLUE}=== WHP Migration: Git to Release System ===${NC}"
echo "This script will migrate your WHP installation from git-based updates to the new release system."
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}Error: This script must be run as root${NC}"
    exit 1
fi

# Check if WHP directory exists
if [ ! -d "$WHP_DIR" ]; then
    echo -e "${RED}Error: WHP directory not found: $WHP_DIR${NC}"
    echo "This script should be run on an existing WHP server."
    exit 1
fi

# Check if this is already a versioned installation
if [ -f "/etc/whp-version" ] || [ -f "$WHP_DIR/VERSION" ]; then
    echo -e "${GREEN}This server already appears to be using the versioned release system.${NC}"
    if [ -f "/etc/whp-version" ]; then
        echo "Current version: $(cat /etc/whp-version)"
    elif [ -f "$WHP_DIR/VERSION" ]; then
        echo "Current version: $(cat $WHP_DIR/VERSION)"
    fi
    exit 0
fi

# Create backup before migration
echo -e "${YELLOW}Creating backup before migration...${NC}"
BACKUP_FILE="/root/whp-pre-migration-backup-$(date +%Y%m%d-%H%M%S).tar.gz"
tar -czf "$BACKUP_FILE" -C / root/whp docker/whp/web 2>/dev/null || true
echo "Backup created: $BACKUP_FILE"

# Detect current git commit for version inference
echo -e "${YELLOW}Detecting current installation...${NC}"
cd "$WHP_DIR"

# Get current commit info
CURRENT_COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
CURRENT_BRANCH=$(git branch --show-current 2>/dev/null || echo "unknown")
GIT_STATUS=$(git status --porcelain 2>/dev/null || echo "unknown")

echo "Current commit: $CURRENT_COMMIT"
echo "Current branch: $CURRENT_BRANCH"

if [ -n "$GIT_STATUS" ]; then
    echo -e "${YELLOW}Warning: There are uncommitted changes in the git repository${NC}"
    echo "$GIT_STATUS"
fi

# Fetch latest from git to prepare for migration
echo -e "${YELLOW}Fetching latest changes from git...${NC}"
git fetch origin || true

# Check if we're behind
BEHIND_COUNT=$(git rev-list --count HEAD..origin/$CURRENT_BRANCH 2>/dev/null || echo "0")
if [ "$BEHIND_COUNT" -gt 0 ]; then
    echo -e "${YELLOW}Your installation is $BEHIND_COUNT commits behind the latest${NC}"
    read -p "Do you want to update to the latest git version before migration? (recommended) [y/N]: " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo "Updating to latest git version..."
        git pull origin $CURRENT_BRANCH
        rsync -av --delete web-files/ $WEB_DIR/
        echo "Updated to latest git version"
    fi
fi

# Download and install the latest release
echo -e "${YELLOW}Downloading latest WHP release...${NC}"

# Get latest version info
LATEST_INFO=$(curl -sf "$RELEASE_SERVER/latest.json" || echo "")
if [ -z "$LATEST_INFO" ]; then
    echo -e "${RED}Error: Unable to fetch latest release information from $RELEASE_SERVER${NC}"
    echo "Please check your internet connection and the release server status."
    exit 1
fi

LATEST_VERSION=$(echo "$LATEST_INFO" | grep -o '"version":"[^"]*' | cut -d'"' -f4)
FILENAME=$(echo "$LATEST_INFO" | grep -o '"filename":"[^"]*' | cut -d'"' -f4)
CHECKSUM=$(echo "$LATEST_INFO" | grep -o '"checksum":"[^"]*' | cut -d'"' -f4)

echo "Latest release: $LATEST_VERSION"
echo "Package: $FILENAME"

# Download the release
cd /tmp
echo "Downloading $FILENAME..."
if ! curl -f -L -o "$FILENAME" "$RELEASE_SERVER/releases/$FILENAME"; then
    echo -e "${RED}Error: Failed to download release package${NC}"
    exit 1
fi

# Verify checksum
echo "Verifying checksum..."
ACTUAL_CHECKSUM=$(sha256sum "$FILENAME" | cut -d' ' -f1)
if [ "$CHECKSUM" != "$ACTUAL_CHECKSUM" ]; then
    echo -e "${RED}Error: Checksum verification failed${NC}"
    echo "Expected: $CHECKSUM"
    echo "Actual: $ACTUAL_CHECKSUM"
    rm "$FILENAME"
    exit 1
fi

echo -e "${GREEN}Checksum verified${NC}"

# Extract the release
echo "Extracting release package..."
tar -xzf "$FILENAME"

# Find extracted directory
EXTRACT_DIR=$(find . -maxdepth 1 -type d -name "whp-release-*" | head -1)
if [ -z "$EXTRACT_DIR" ] || [ ! -d "$EXTRACT_DIR" ]; then
    echo -e "${RED}Error: Failed to extract release package${NC}"
    exit 1
fi

cd "$EXTRACT_DIR"

# Update the repository directory with new files
echo -e "${YELLOW}Installing new WHP files...${NC}"

# Copy new scripts and system files (but preserve git history)
rsync -av --exclude='sql/migrations/' --exclude='.git' ./ "$WHP_DIR/"

# Update web files
rsync -av --delete web-files/ "$WEB_DIR/"

# Set proper permissions
chown -R apache:apache "$WEB_DIR/"
find "$WEB_DIR" -type d -exec chmod 755 {} \;
find "$WEB_DIR" -type f -exec chmod 644 {} \;

# Make scripts executable
chmod +x "$WHP_DIR"/scripts/*.sh
chmod +x "$WHP_DIR"/update.sh

# Create version files
echo "$LATEST_VERSION" > "$WHP_DIR/VERSION"
echo "$LATEST_VERSION" > "/etc/whp-version"

# Apply any new migrations that might be needed
echo -e "${YELLOW}Checking for database migrations...${NC}"
if [ -d "$WHP_DIR/sql/migrations/$LATEST_VERSION" ]; then
    echo "Applying migrations for version $LATEST_VERSION..."
    for migration in "$WHP_DIR/sql/migrations/$LATEST_VERSION"/*.sql; do
        if [ -f "$migration" ]; then
            echo "  - Running: $(basename "$migration")"
            mysql < "$migration" || echo "    Warning: Migration may have failed"
        fi
    done
else
    echo "No migrations needed for version $LATEST_VERSION"
fi

# Update git repository to track version (optional)
cd "$WHP_DIR"
if [ -d ".git" ]; then
    echo -e "${YELLOW}Updating git repository...${NC}"
    git add VERSION update.sh scripts/
    if git diff --staged --quiet; then
        echo "No new files to commit to git"
    else
        git commit -m "Migrate to release system v$LATEST_VERSION

- Added VERSION file for release tracking
- Added new update system scripts
- Migration from git-based to release-based updates

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>" || echo "Git commit skipped"
    fi
fi

# Restart services to ensure everything is working
echo -e "${YELLOW}Restarting services...${NC}"
systemctl restart httpd php-fpm

# Cleanup
cd /
rm -rf "/tmp/$FILENAME" "/tmp/$EXTRACT_DIR"

# Test the new system
echo -e "${YELLOW}Testing new release system...${NC}"
if [ -x "$WHP_DIR/scripts/download-update.sh" ]; then
    echo "Testing update check..."
    if "$WHP_DIR/scripts/download-update.sh" --help >/dev/null 2>&1; then
        echo -e "${GREEN}✓ Update script is working${NC}"
    else
        echo -e "${RED}✗ Update script test failed${NC}"
    fi
fi

# Test web interface access
if curl -sf "http://localhost/" >/dev/null 2>&1; then
    echo -e "${GREEN}✓ Web interface is accessible${NC}"
else
    echo -e "${YELLOW}Warning: Web interface test failed (may be normal)${NC}"
fi

# Final summary
echo ""
echo -e "${GREEN}=== Migration Complete ===${NC}"
echo ""
echo "WHP has been successfully migrated to the release system!"
echo ""
echo "Migration Summary:"
echo "  Previous system: Git-based updates"
echo "  New system: Release-based updates"
echo "  Current version: $LATEST_VERSION"
echo "  Version files: /etc/whp-version and $WHP_DIR/VERSION"
echo "  Backup created: $BACKUP_FILE"
echo ""
echo "Update Commands:"
echo "  Check for updates: $WHP_DIR/scripts/download-update.sh"
echo "  Auto-update: $WHP_DIR/scripts/download-update.sh --auto"
echo "  Manual update: Download tar.gz and run ./update.sh"
echo ""
echo "Web Interface:"
echo "  The update management page will now use the release system"
echo "  Git-based updates are still available but deprecated"
echo ""
echo -e "${YELLOW}Next Steps:${NC}"
echo "1. Test the web interface update management page"
echo "2. Set up automatic updates via cron (optional):"
echo "   0 3 * * * $WHP_DIR/scripts/download-update.sh --auto >> /var/log/whp-auto-update.log 2>&1"
echo "3. Monitor the first few updates to ensure they work correctly"
echo ""
echo -e "${GREEN}Migration successful! Your WHP server is now using the release system.${NC}"