#!/bin/bash
# WHP Update Downloader
# Downloads and applies the latest WHP update

# 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
UPDATE_URL="https://whp-releases.cloud-hosting.io"
TEMP_DIR="/tmp/whp-update-$$"

# Parse command line arguments
AUTO_MODE=false
FORCE_VERSION=""
while [[ $# -gt 0 ]]; do
    case $1 in
        --auto)
            AUTO_MODE=true
            shift
            ;;
        --version)
            FORCE_VERSION="$2"
            shift 2
            ;;
        --help)
            echo "Usage: $0 [options]"
            echo "Options:"
            echo "  --auto          Run in automatic mode (no prompts)"
            echo "  --version X     Force update to specific version"
            echo "  --help          Show this help message"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Function to cleanup on exit
cleanup() {
    rm -rf "$TEMP_DIR"
}
trap cleanup EXIT

# Check if WHP is installed
if [ ! -f /etc/whp-version ] && [ ! -f /root/whp/VERSION ]; then
    echo -e "${RED}Error: WHP not installed${NC}"
    echo "Please run setup.sh for new installations"
    exit 1
fi

# Get current version
if [ -f /etc/whp-version ]; then
    CURRENT_VERSION=$(cat /etc/whp-version)
elif [ -f /root/whp/VERSION ]; then
    CURRENT_VERSION=$(cat /root/whp/VERSION)
fi

echo -e "${BLUE}WHP Update Check${NC}"
echo "Current version: $CURRENT_VERSION"

# Check for updates
echo "Checking for updates..."
LATEST_INFO=$(curl -sf "$UPDATE_URL/latest.json" || echo "")

if [ -z "$LATEST_INFO" ]; then
    echo -e "${RED}Error: Unable to check for updates${NC}"
    echo "Please check your internet connection or try again later"
    exit 1
fi

# Parse JSON (basic parsing without jq)
LATEST_VERSION=$(echo "$LATEST_INFO" | grep '"version":' | cut -d'"' -f4)
FILENAME=$(echo "$LATEST_INFO" | grep '"filename":' | cut -d'"' -f4)
CHECKSUM=$(echo "$LATEST_INFO" | grep '"checksum":' | cut -d'"' -f4)
FILE_SIZE=$(echo "$LATEST_INFO" | grep '"size":' | cut -d':' -f2 | tr -d ' ,')

# If specific version requested, override
if [ -n "$FORCE_VERSION" ]; then
    echo "Forcing update to version: $FORCE_VERSION"
    LATEST_VERSION="$FORCE_VERSION"
    FILENAME="whp-$FORCE_VERSION.tar.gz"
    
    # Get metadata for specific version
    VERSION_INFO=$(curl -sf "$UPDATE_URL/releases/whp-$FORCE_VERSION.json" || echo "")
    if [ -z "$VERSION_INFO" ]; then
        echo -e "${RED}Error: Version $FORCE_VERSION not found${NC}"
        exit 1
    fi
    
    CHECKSUM=$(echo "$VERSION_INFO" | grep '"checksum":' | cut -d'"' -f4)
    FILE_SIZE=$(echo "$VERSION_INFO" | grep '"size":' | cut -d':' -f2 | tr -d ' ,')
fi

echo "Latest version: $LATEST_VERSION"

# Check if update is needed
if [ "$CURRENT_VERSION" = "$LATEST_VERSION" ] && [ -z "$FORCE_VERSION" ]; then
    echo -e "${GREEN}Already running latest version${NC}"
    exit 0
fi

# Convert size to human readable
if command -v numfmt >/dev/null 2>&1; then
    HUMAN_SIZE=$(numfmt --to=iec-i --suffix=B $FILE_SIZE 2>/dev/null || echo "$FILE_SIZE bytes")
else
    HUMAN_SIZE="$FILE_SIZE bytes"
fi

echo ""
echo "Update available: $CURRENT_VERSION → $LATEST_VERSION"
echo "Download size: $HUMAN_SIZE"

# In auto mode, proceed without confirmation
if [ "$AUTO_MODE" = false ]; then
    read -p "Download and install update? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Update cancelled"
        exit 0
    fi
fi

# Create temp directory
mkdir -p "$TEMP_DIR"
cd "$TEMP_DIR"

# Download update
echo ""
echo "Downloading update..."
DOWNLOAD_URL="$UPDATE_URL/releases/$FILENAME"

if ! curl -f -L -o "$FILENAME" "$DOWNLOAD_URL"; then
    echo -e "${RED}Error: Failed to download update${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"
    exit 1
fi

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

# Extract update
echo "Extracting update..."
tar -xzf "$FILENAME"

# Find the extracted directory (should be whp-release-VERSION)
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 update package${NC}"
    exit 1
fi

cd "$EXTRACT_DIR"

# Run the update script
echo ""
echo "Running update process..."

if [ "$AUTO_MODE" = true ]; then
    # In auto mode, provide 'y' to confirmation prompt
    echo "y" | ./update.sh 2>&1 || {
        # Handle pipe error gracefully - update may have succeeded
        EXIT_CODE=$?
        if [ $EXIT_CODE -eq 141 ]; then
            # Exit code 141 = SIGPIPE, which is expected when 'echo y' pipe is closed
            echo "Update process completed (pipe closed normally)"
        else
            echo "Update failed with exit code: $EXIT_CODE"
            exit $EXIT_CODE
        fi
    }
else
    ./update.sh
fi

# Update succeeded if we get here
echo ""
echo -e "${GREEN}Update completed successfully!${NC}"

# Log the update if in auto mode
if [ "$AUTO_MODE" = true ]; then
    echo "[$(date)] Updated from $CURRENT_VERSION to $LATEST_VERSION" >> /var/log/whp-auto-update.log
fi