#!/bin/bash
#
# WebDrop Bridge Release Downloader
#
# Download WebDrop Bridge release installer from Forgejo via wget.
# Useful for enterprise deployments, automated scripts, and initial setup.
#
# Usage:
#   ./download_release.sh                  # Download latest to current dir
#   ./download_release.sh 0.8.0            # Download specific version
#   ./download_release.sh latest ~/Downloads  # Download to specific directory
#   ./download_release.sh --no-verify      # Skip checksum verification
#

set -euo pipefail

# Configuration
FORGEJO_URL="https://git.him-tools.de"
REPO="HIM-public/webdrop-bridge"
VERSION="${1:-latest}"
OUTPUT_DIR="${2:-.}"
VERIFY_CHECKSUM=true

# Handle flags
if [[ "$VERSION" == "--no-verify" ]]; then
    VERIFY_CHECKSUM=false
    VERSION="latest"
    OUTPUT_DIR="${2:-.}"
fi

if [[ "$VERSION" == "--no-verify" ]]; then
    VERIFY_CHECKSUM=false
    VERSION="latest"
    OUTPUT_DIR="${2:-.}"
elif [[ ! "$VERSION" =~ ^[0-9\.a-z-]+$ ]] && [[ "$VERSION" != "latest" ]]; then
    # Treat any non-version argument as output dir
    OUTPUT_DIR="$VERSION"
    VERSION="latest"
fi

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

# Create output directory
mkdir -p "$OUTPUT_DIR"
OUTPUT_DIR="$(cd "$OUTPUT_DIR" && pwd)"

echo -e "${CYAN}🚀 WebDrop Bridge Download Script${NC}"
echo -e "Version: $VERSION"
echo -e "Output: $OUTPUT_DIR"
echo ""

# Check if wget is installed
if ! command -v wget &> /dev/null; then
    echo -e "${RED}❌ wget not found. Install via:${NC}"
    echo -e "${YELLOW}   macOS: brew install wget${NC}"
    echo -e "${YELLOW}   Linux: apt-get install wget (Ubuntu/Debian) or equivalent${NC}"
    exit 1
fi

WGET_VERSION=$(wget --version | head -n1)
echo -e "${GREEN}✓ wget found: $WGET_VERSION${NC}"
echo ""

# Fetch release info from Forgejo API
API_ENDPOINT="$FORGEJO_URL/api/v1/repos/$REPO/releases/$VERSION"
echo -e "${CYAN}📥 Fetching release information from Forgejo...${NC}"

RELEASE_JSON=$(wget -q -O - "$API_ENDPOINT" 2>/dev/null || {
    echo -e "${RED}❌ Failed to fetch release info from $API_ENDPOINT${NC}"
    exit 1
})

if [[ -z "$RELEASE_JSON" ]]; then
    echo -e "${RED}❌ Release not found: $VERSION${NC}"
    exit 1
fi

# Parse JSON (basic shell parsing, suitable for our use case)
TAG_NAME=$(echo "$RELEASE_JSON" | grep -o '"tag_name":"[^"]*"' | head -1 | cut -d'"' -f4)
RELEASE_NAME=$(echo "$RELEASE_JSON" | grep -o '"name":"[^"]*"' | head -1 | cut -d'"' -f4)

if [[ -z "$TAG_NAME" ]]; then
    echo -e "${RED}❌ Failed to parse release information${NC}"
    exit 1
fi

echo -e "${GREEN}📦 Found release: $RELEASE_NAME ($TAG_NAME)${NC}"
echo ""

# Find installer asset (.msi for Windows, .dmg for macOS)
# Extract all asset names and URLs
INSTALLER_NAME=""
INSTALLER_URL=""
CHECKSUM_URL=""

# macOS systems prefer .dmg, Windows/.msi
SYSTEM=$(uname -s)
if [[ "$SYSTEM" == "Darwin" ]]; then
    # macOS: prefer .dmg
    INSTALLER_NAME=$(echo "$RELEASE_JSON" | grep -o '"name":"[^"]*\.dmg"' | head -1 | cut -d'"' -f4)
    if [[ -z "$INSTALLER_NAME" ]]; then
        # Fallback to .msi if no .dmg
        INSTALLER_NAME=$(echo "$RELEASE_JSON" | grep -o '"name":"[^"]*\.msi"' | head -1 | cut -d'"' -f4)
    fi
else
    # Linux/Other: prefer .msi, fallback to .dmg
    INSTALLER_NAME=$(echo "$RELEASE_JSON" | grep -o '"name":"[^"]*\.msi"' | head -1 | cut -d'"' -f4)
    if [[ -z "$INSTALLER_NAME" ]]; then
        INSTALLER_NAME=$(echo "$RELEASE_JSON" | grep -o '"name":"[^"]*\.dmg"' | head -1 | cut -d'"' -f4)
    fi
fi

if [[ -z "$INSTALLER_NAME" ]]; then
    echo -e "${RED}❌ No installer found in release (looking for .msi or .dmg)${NC}"
    exit 1
fi

# Extract browser_download_url for installer
# This is a bit hacky but works for JSON without a full JSON parser
INSTALLER_URL=$(echo "$RELEASE_JSON" | \
    grep -B2 "\"name\":\"$INSTALLER_NAME\"" | \
    grep -o '"browser_download_url":"[^"]*"' | \
    cut -d'"' -f4)

if [[ -z "$INSTALLER_URL" ]]; then
    echo -e "${RED}❌ Could not extract download URL for $INSTALLER_NAME${NC}"
    exit 1
fi

# Find checksum URL if verification is enabled
if [[ "$VERIFY_CHECKSUM" == "true" ]]; then
    CHECKSUM_FILENAME="${INSTALLER_NAME}.sha256"
    CHECKSUM_URL=$(echo "$RELEASE_JSON" | \
        grep -B2 "\"name\":\"$CHECKSUM_FILENAME\"" | \
        grep -o '"browser_download_url":"[^"]*"' | \
        cut -d'"' -f4 || echo "")
fi

INSTALLER_PATH="$OUTPUT_DIR/$INSTALLER_NAME"

echo -e "${CYAN}💾 Downloading: $INSTALLER_NAME${NC}"
echo -e "${CYAN}   URL: $INSTALLER_URL${NC}"
echo ""

# Download using wget with progress
if ! wget -O "$INSTALLER_PATH" "$INSTALLER_URL" --show-progress 2>&1; then
    echo -e "${RED}❌ Download failed${NC}"
    [[ -f "$INSTALLER_PATH" ]] && rm -f "$INSTALLER_PATH"
    exit 1
fi

echo ""
echo -e "${GREEN}✓ Downloaded: $INSTALLER_PATH${NC}"

# Verify checksum if requested and available
if [[ "$VERIFY_CHECKSUM" == "true" ]] && [[ -n "$CHECKSUM_URL" ]]; then
    echo ""
    echo -e "${CYAN}🔍 Verifying checksum...${NC}"
    
    CHECKSUM_PATH="$OUTPUT_DIR/${INSTALLER_NAME}.sha256"
    
    if wget -O "$CHECKSUM_PATH" "$CHECKSUM_URL" -q 2>/dev/null; then
        # Read checksum from file (format: "hash  filename")
        EXPECTED_HASH=$(cut -d' ' -f1 "$CHECKSUM_PATH")
        
        # Calculate SHA256
        if command -v sha256sum &> /dev/null; then
            ACTUAL_HASH=$(sha256sum "$INSTALLER_PATH" | cut -d' ' -f1)
        elif command -v shasum &> /dev/null; then
            ACTUAL_HASH=$(shasum -a 256 "$INSTALLER_PATH" | cut -d' ' -f1)
        else
            echo -e "${YELLOW}⚠ No SHA256 tool available, skipping verification${NC}"
            ACTUAL_HASH=""
        fi
        
        if [[ -n "$ACTUAL_HASH" ]]; then
            if [[ "${EXPECTED_HASH,,}" == "${ACTUAL_HASH,,}" ]]; then
                echo -e "${GREEN}✓ Checksum verified${NC}"
            else
                echo -e "${RED}❌ Checksum mismatch!${NC}"
                echo -e "${YELLOW}   Expected: $EXPECTED_HASH${NC}"
                echo -e "${YELLOW}   Actual:   $ACTUAL_HASH${NC}"
                rm -f "$INSTALLER_PATH" "$CHECKSUM_PATH"
                exit 1
            fi
        fi
        
        rm -f "$CHECKSUM_PATH"
    else
        echo -e "${YELLOW}⚠ Could not download checksum file, skipping verification${NC}"
    fi
elif [[ "$VERIFY_CHECKSUM" == "true" ]]; then
    echo -e "${YELLOW}⚠ No checksum file in release, skipping verification${NC}"
fi

echo ""
echo -e "${GREEN}✅ Download complete!${NC}"
echo ""
echo -e "${CYAN}Next steps:${NC}"
echo -e "  1. Review: $INSTALLER_PATH"
echo -e "  2. Execute installer to install WebDrop Bridge"
echo -e "  3. Launch application and configure paths/URLs in settings"
echo ""
