#!/bin/bash
# WHP Release Builder
# Builds tar.gz release packages for distribution

# Exit on any error
set -e

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

# Get the directory where this script is located
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Change to project root
cd "$PROJECT_ROOT"

# Check if VERSION file exists
if [ ! -f VERSION ]; then
    echo -e "${RED}Error: VERSION file not found${NC}"
    exit 1
fi

VERSION=$(cat VERSION)
RELEASE_DIR="/tmp/whp-release-$VERSION"
RELEASES_PATH="/var/www/whp-releases"

echo -e "${GREEN}Building WHP Release $VERSION${NC}"

# Clean and create temp directory
echo "Creating temporary build directory..."
rm -rf "$RELEASE_DIR"
mkdir -p "$RELEASE_DIR"

# Files and directories to exclude from release
EXCLUDE_PATTERNS=(
    '.git'
    '.gitignore'
    '.gitea/'
    '.cursorrules'
    'docs/'
    '*.md'
    '.dev/'
    'NextSteps.md'
    'CLAUDE.md'
    'Notes/'
    '.build-exclude'
    'test/'
    '*.log'
    '.DS_Store'
    'release-server/'
    'how_to_get_container_ip_range.txt'
    'memories.md'
    'cursor_rules.md'
    'database_schema.md'
    'PERMISSION_SYSTEM.md'
)

# Build rsync exclude arguments
RSYNC_EXCLUDES=""
for pattern in "${EXCLUDE_PATTERNS[@]}"; do
    RSYNC_EXCLUDES="$RSYNC_EXCLUDES --exclude=$pattern"
done

# Copy production files
echo "Copying production files..."
rsync -av $RSYNC_EXCLUDES ./ "$RELEASE_DIR/"

# Ensure required directories exist in release
mkdir -p "$RELEASE_DIR/sql/migrations"

# Get list of all migration directories sorted by version
if [ -d "sql/migrations" ]; then
    cd "$PROJECT_ROOT/sql/migrations"
    MIGRATIONS=($(ls -d */ 2>/dev/null | sed 's/\///' | sort -V))
    cd "$PROJECT_ROOT"
    
    TOTAL=${#MIGRATIONS[@]}
    echo "Found $TOTAL migration versions"
    
    if [ $TOTAL -gt 10 ]; then
        # Keep only the last 10 versions
        echo -e "${YELLOW}Trimming to last 10 migration versions${NC}"
        KEEP_FROM=$((TOTAL - 10))
        
        # Copy only the last 10 versions
        for ((i=$KEEP_FROM; i<$TOTAL; i++)); do
            echo "  Including: ${MIGRATIONS[$i]}"
            cp -r "sql/migrations/${MIGRATIONS[$i]}" "$RELEASE_DIR/sql/migrations/"
        done
        
        OLDEST_VERSION="${MIGRATIONS[$KEEP_FROM]}"
    else
        # Copy all migrations
        if [ $TOTAL -gt 0 ]; then
            cp -r sql/migrations/* "$RELEASE_DIR/sql/migrations/" 2>/dev/null || true
            OLDEST_VERSION="${MIGRATIONS[0]}"
        else
            OLDEST_VERSION="$VERSION"
        fi
    fi
else
    echo -e "${YELLOW}No migrations directory found${NC}"
    OLDEST_VERSION="$VERSION"
fi

# Create migration history file
echo "Creating migration history..."
cat > "$RELEASE_DIR/MIGRATION_HISTORY.json" <<EOF
{
  "current_version": "$VERSION",
  "oldest_supported": "$OLDEST_VERSION",
  "migration_count": $(ls -d "$RELEASE_DIR"/sql/migrations/*/ 2>/dev/null | wc -l || echo 0),
  "build_date": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "build_host": "$(hostname)"
}
EOF

# Create tar.gz
echo "Creating release archive..."
cd /tmp
tar -czf "whp-$VERSION.tar.gz" "whp-release-$VERSION/"

# Calculate file size and checksum
FILE_SIZE=$(stat -c%s "whp-$VERSION.tar.gz" 2>/dev/null || stat -f%z "whp-$VERSION.tar.gz" 2>/dev/null)
FILE_CHECKSUM=$(sha256sum "whp-$VERSION.tar.gz" | cut -d' ' -f1)

echo -e "${GREEN}Release package created:${NC}"
echo "  File: whp-$VERSION.tar.gz"
echo "  Size: $(numfmt --to=iec-i --suffix=B $FILE_SIZE 2>/dev/null || echo "$FILE_SIZE bytes")"
echo "  SHA256: $FILE_CHECKSUM"

# If releases path exists (on build server), deploy it
if [ -d "$RELEASES_PATH" ]; then
    echo "Deploying to releases directory..."
    mkdir -p "$RELEASES_PATH/releases"
    mv "whp-$VERSION.tar.gz" "$RELEASES_PATH/releases/"
    
    # Create metadata file
    cat > "$RELEASES_PATH/releases/whp-$VERSION.json" <<EOF
{
  "version": "$VERSION",
  "filename": "whp-$VERSION.tar.gz",
  "size": $FILE_SIZE,
  "checksum": "$FILE_CHECKSUM",
  "oldest_supported": "$OLDEST_VERSION",
  "release_date": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
EOF
    
    # Update latest.json
    cp "$RELEASES_PATH/releases/whp-$VERSION.json" "$RELEASES_PATH/latest.json"
    
    echo -e "${GREEN}Release deployed to whp-releases.cloud-hosting.io${NC}"
else
    # Keep the file in /tmp for manual deployment
    echo -e "${YELLOW}Release package saved to: /tmp/whp-$VERSION.tar.gz${NC}"
    echo "Deploy manually to your release server"
    
    # Also create the metadata file
    cat > "/tmp/whp-$VERSION.json" <<EOF
{
  "version": "$VERSION",
  "filename": "whp-$VERSION.tar.gz",
  "size": $FILE_SIZE,
  "checksum": "$FILE_CHECKSUM",
  "oldest_supported": "$OLDEST_VERSION",
  "release_date": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
EOF
    echo "Metadata saved to: /tmp/whp-$VERSION.json"
fi

# Cleanup
rm -rf "$RELEASE_DIR"

echo -e "${GREEN}Build complete!${NC}"