#!/bin/bash
# upload.sh
# Usage: ./upload.sh <command> <upload_file_name> <local_file>

set -e

if [ "$#" -lt 1 ]; then
    echo "Usage: $0 <command(remove/upload/update)> <upload_file_name>? <local_file>?"
    exit 1
fi

COMMAND="$1"
UPLOAD_NAME="$2"
LOCAL_FILE="$3"

BUCKET="eat-shit-and-die-lang.tufts.me"
RELEASES_PREFIX="releases/"
CURRENT_RELEASE_KEY="current-release/esad-lang-beta.zip"
INDEX_FILE="index.html"

# Function to extract version, date, and notes from a zip file
get_changelog() {
    local file="$1"
    # send debug to stderr so it is visible even when caller captures stdout

    rm -rf ./curr-unzip
    unzip -qq "$file" -d ./curr-unzip

    local changelog_file="./curr-unzip/esad-lang/changelog.txt"
    if [ -f "$changelog_file" ]; then
        local version date notes
        version=$(grep "^Version:" "$changelog_file" | cut -d':' -f2 | xargs)
        date=$(grep "^Date:" "$changelog_file" | cut -d':' -f2 | xargs)

        # Extract everything after "Notes:" until the end of file
        notes=$(awk '/^Notes:/ {flag=1; next} flag {print}' "$changelog_file" | sed 's/^[ \t]*-//')

        # Trim leading/trailing whitespace from notes lines
        notes=$(echo "$notes" | sed '/^\s*$/d' | sed 's/^[ \t]*//')

        # Return as a delimited string
        echo "$version|$date|$notes"
    fi
}

# Function to rebuild index.html
update_index_html() {
    # Download index.html or create placeholder
    if ! aws s3 cp "s3://$BUCKET/$INDEX_FILE" "$INDEX_FILE"; then
        echo "<!DOCTYPE html><html><head><title>ESAD Website</title></head><body><h1>Welcome to the ESAD Lang website</h1></body></html>" > "$INDEX_FILE"
    fi
    echo "📥 Downloaded index.html"

    # List all releases in S3
    RELEASE_FILES=$(aws s3 ls "s3://$BUCKET/$RELEASES_PREFIX" | awk '{print $4}' | sort -r)
    RELEASE_LIST=""
    for f in $RELEASE_FILES; do

        aws s3 cp "s3://$BUCKET/$RELEASES_PREFIX$f" curr-zip

        # Parse version, date, notes from zip (function returns "version|date|notes")
        output="$(get_changelog curr-zip)"

        # Split the delimited output into variables
        IFS='|' read -r version date notes <<< "$output"

        # Debug output (visible to terminal)
        echo "Processing $f"
        echo "version: $version"
        echo "date: $date"
        echo "notes:"
        echo "$notes"

        # Build release entry: clickable filename with date
        RELEASE_LIST+="<a href=\"${RELEASES_PREFIX}${f}\" download>${f}</a> - ${date}"$'\n'
        while IFS= read -r line; do
            RELEASE_LIST+=$'\t'"$line"$'\n'
        done <<< "$notes"
        RELEASE_LIST+=$'\n'

        # cleanup temporary files produced during processing
        rm -f curr-zip
        rm -rf curr-unzip
    done

    # Write index.html with preformatted release list
    cat > "$INDEX_FILE" <<EOF
<!DOCTYPE html>
<html>
<head>
    <title>ESAD Website</title>
    <style>pre { white-space: pre-wrap; font-family: monospace; }</style>
</head>
<body>
    <h1>Welcome to the ESAD Lang website</h1>

    <h2>Current Release</h2>
    <a href="current-release/esad-lang-beta.zip" download>
        <button>Download Latest Version</button>
    </a>

    <h2>All Releases</h2>
    <pre>
$RELEASE_LIST
    </pre>
</body>
</html>
EOF

    aws s3 cp "$INDEX_FILE" "s3://$BUCKET/$INDEX_FILE"
    rm "$INDEX_FILE"
    echo "📝 index.html updated"
}

# Remove a release
remove_release() {
    aws s3 rm "s3://$BUCKET/$RELEASES_PREFIX$UPLOAD_NAME"
    echo "🗑️ Removed $UPLOAD_NAME from S3"
    update_index_html
}

# Upload a release
upload_release() {
    aws s3 cp "$LOCAL_FILE" "s3://$BUCKET/$RELEASES_PREFIX$UPLOAD_NAME" --acl public-read
    echo "✅ Uploaded $LOCAL_FILE to s3://$BUCKET/$RELEASES_PREFIX$UPLOAD_NAME"

    aws s3 cp "$LOCAL_FILE" "s3://$BUCKET/$CURRENT_RELEASE_KEY" --acl public-read
    echo "📦 Updated current release"

    update_index_html
}

# Command dispatcher
case "$COMMAND" in
    upload)
        upload_release
        ;;
    remove)
        remove_release
        ;;
    update)
        update_index_html
        ;;
    --version)
        echo "I don't handle versioning on ts, dumbass"
        exit 0
        ;;
    help)
        echo "Usage: $0 <command(remove/upload/update)> <upload_file_name>? <local_file>?"
        echo "Commands:"
        echo "  upload <upload_file_name> <local_file>  - Uploads a new release"
        echo "  remove <upload_file_name>                - Removes a release"
        echo "  update                                   - Updates the index.html file"
        exit 0
        ;;
    upgrade)
        sudo cp esad-lang/src/💩☁️ /usr/local/bin/💩☁️
        exit 1
        ;;
    *)
        echo "Invalid command. Please use 'upload', 'remove', or 'update'."
        exit 1
        ;;
esac
