#!/bin/bash
# Create Forgejo Release with Binary Assets
# Usage: ./create_release.sh -v 1.0.0
# Uses your Forgejo credentials (same as git)
# First run will prompt for credentials and save them to this session

set -e

# Parse arguments
VERSION=""
FORGEJO_USER=""
FORGEJO_PASS=""
FORGEJO_URL="https://git.him-tools.de"
REPO="HIM-public/webdrop-bridge"
DMG_PATH="build/dist/macos/WebDropBridge.dmg"
CHECKSUM_PATH="build/dist/macos/WebDropBridge.dmg.sha256"
CLEAR_CREDS=false

while [[ $# -gt 0 ]]; do
    case $1 in
        -v|--version) VERSION="$2"; shift 2;;
        -u|--url) FORGEJO_URL="$2"; shift 2;;
        --clear-credentials) CLEAR_CREDS=true; shift;;
        *) echo "Unknown option: $1"; exit 1;;
    esac
done

# Handle --clear-credentials flag
if [ "$CLEAR_CREDS" = true ]; then
    unset FORGEJO_USER
    unset FORGEJO_PASS
    echo "[OK] Credentials cleared from this session"
    exit 0
fi

# Load credentials from environment
FORGEJO_USER="${FORGEJO_USER}"
FORGEJO_PASS="${FORGEJO_PASS}"

# Verify required parameters
if [ -z "$VERSION" ]; then
    echo "ERROR: Version parameter required" >&2
    echo "Usage: $0 -v VERSION [-u FORGEJO_URL]" >&2
    echo "Example: $0 -v 1.0.0" >&2
    exit 1
fi

# If no credentials, prompt user interactively
if [ -z "$FORGEJO_USER" ] || [ -z "$FORGEJO_PASS" ]; then
    echo "Forgejo credentials not found. Enter your credentials:"
    
    if [ -z "$FORGEJO_USER" ]; then
        read -p "Username: " FORGEJO_USER
    fi
    
    if [ -z "$FORGEJO_PASS" ]; then
        read -sp "Password: " FORGEJO_PASS
        echo ""
    fi
    
    # Export for this session
    export FORGEJO_USER
    export FORGEJO_PASS
    echo "[OK] Credentials saved to this shell session"
    echo "Tip: Credentials will persist until you close the terminal or run: $0 --clear-credentials"
fi

# Verify files exist
if [ ! -f "$DMG_PATH" ]; then
    echo "ERROR: DMG file not found at $DMG_PATH"
    exit 1
fi

if [ ! -f "$CHECKSUM_PATH" ]; then
    echo "ERROR: Checksum file not found at $CHECKSUM_PATH"
    exit 1
fi

echo "Creating WebDropBridge $VERSION release on Forgejo..."

# Get file info
DMG_SIZE=$(du -m "$DMG_PATH" | cut -f1)
CHECKSUM=$(cat "$CHECKSUM_PATH")

echo "File: WebDropBridge.dmg ($DMG_SIZE MB)"
echo "Checksum: ${CHECKSUM:0:16}..."

# Create basic auth
BASIC_AUTH=$(echo -n "${FORGEJO_USER}:${FORGEJO_PASS}" | base64)

# Step 1: Create release
echo ""
echo "Creating release v$VERSION..."
RELEASE_URL="$FORGEJO_URL/api/v1/repos/$REPO/releases"

RELEASE_DATA=$(cat <<EOF
{
  "tag_name": "v$VERSION",
  "name": "WebDropBridge v$VERSION",
  "body": "WebDropBridge v$VERSION\n\nChecksum: $CHECKSUM",
  "draft": false,
  "prerelease": false
}
EOF
)

RESPONSE=$(curl -s -X POST \
    -H "Authorization: Basic $BASIC_AUTH" \
    -H "Content-Type: application/json" \
    -d "$RELEASE_DATA" \
    "$RELEASE_URL")

RELEASE_ID=$(echo "$RESPONSE" | grep -o '"id":[0-9]*' | head -1 | cut -d':' -f2)

if [ -z "$RELEASE_ID" ]; then
    echo "ERROR creating release:"
    echo "$RESPONSE"
    exit 1
fi

echo "[OK] Release created (ID: $RELEASE_ID)"

# Step 2: Upload DMG as asset
echo "Uploading executable asset..."
UPLOAD_URL="$FORGEJO_URL/api/v1/repos/$REPO/releases/$RELEASE_ID/assets"

HTTP_CODE=$(curl -s -w "%{http_code}" -X POST \
    -H "Authorization: Basic $BASIC_AUTH" \
    -F "attachment=@$DMG_PATH" \
    "$UPLOAD_URL" \
    -o /tmp/curl_response.txt)

if [ "$HTTP_CODE" -eq 201 ] || [ "$HTTP_CODE" -eq 200 ]; then
    echo "[OK] DMG uploaded"
else
    echo "ERROR uploading DMG (HTTP $HTTP_CODE)"
    cat /tmp/curl_response.txt
    exit 1
fi

# Step 3: Upload checksum as asset
echo "Uploading checksum asset..."

HTTP_CODE=$(curl -s -w "%{http_code}" -X POST \
    -H "Authorization: Basic $BASIC_AUTH" \
    -F "attachment=@$CHECKSUM_PATH" \
    "$UPLOAD_URL" \
    -o /tmp/curl_response.txt)

if [ "$HTTP_CODE" -eq 201 ] || [ "$HTTP_CODE" -eq 200 ]; then
    echo "[OK] Checksum uploaded"
else
    echo "ERROR uploading checksum (HTTP $HTTP_CODE)"
    cat /tmp/curl_response.txt
    exit 1
fi

echo ""
echo "[OK] Release complete!"
echo "View at: $FORGEJO_URL/$REPO/releases/tag/v$VERSION"
