#!/bin/bash

# Tasq Release Script
# Creates a signed release build and GitHub release
# 
# Usage: ./release.sh VERSION "Release notes"
# Example: ./release.sh 0.2.4 "Added new features and bug fixes"

set -e

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

# Configuration
PROJECT_NAME="Tasq"
SCHEME="Tasq"
BUILD_DIR="./build"
ARCHIVE_PATH="$BUILD_DIR/${PROJECT_NAME}.xcarchive"
EXPORT_PATH="$BUILD_DIR"
APP_NAME="${PROJECT_NAME}.app"
ZIP_NAME="${PROJECT_NAME}.app.zip"

# Check arguments
if [ $# -lt 2 ]; then
    echo -e "${RED}Error: Missing arguments${NC}"
    echo "Usage: $0 VERSION \"Release notes\""
    echo "Example: $0 0.2.4 \"Added new features\""
    exit 1
fi

VERSION=$1
RELEASE_NOTES=$2
TAG="v${VERSION}"

echo -e "${GREEN}=== Tasq Release Script ===${NC}"
echo -e "Version: ${YELLOW}${VERSION}${NC}"
echo -e "Tag: ${YELLOW}${TAG}${NC}"
echo ""

# Check if we have required tools
command -v xcodebuild >/dev/null 2>&1 || { echo -e "${RED}Error: xcodebuild not found${NC}"; exit 1; }
command -v gh >/dev/null 2>&1 || { echo -e "${YELLOW}Warning: GitHub CLI (gh) not found. You'll need to create the release manually.${NC}"; }

# Check for Sparkle tools
if [ ! -f "./sign_update" ]; then
    echo -e "${YELLOW}Warning: sign_update tool not found in current directory${NC}"
    echo "Download from: https://github.com/sparkle-project/Sparkle/releases"
    echo "You'll need to sign the update manually"
fi

# Clean previous builds
echo -e "${GREEN}Cleaning previous builds...${NC}"
rm -rf "$BUILD_DIR"
mkdir -p "$BUILD_DIR"

# Build the archive
echo -e "${GREEN}Creating archive...${NC}"
xcodebuild archive \
    -project "${PROJECT_NAME}.xcodeproj" \
    -scheme "$SCHEME" \
    -configuration Release \
    -archivePath "$ARCHIVE_PATH" \
    | xcpretty || xcodebuild archive \
        -project "${PROJECT_NAME}.xcodeproj" \
        -scheme "$SCHEME" \
        -configuration Release \
        -archivePath "$ARCHIVE_PATH"

# Check if we need to create ExportOptions.plist
if [ ! -f "ExportOptions.plist" ]; then
    echo -e "${GREEN}Creating ExportOptions.plist...${NC}"
    cat > ExportOptions.plist << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>method</key>
    <string>mac-application</string>
    <key>teamID</key>
    <string>YOUR_TEAM_ID</string>
    <key>uploadBitcode</key>
    <false/>
    <key>uploadSymbols</key>
    <true/>
    <key>compileBitcode</key>
    <false/>
</dict>
</plist>
EOF
fi

# Export the archive
echo -e "${GREEN}Exporting application...${NC}"
xcodebuild -exportArchive \
    -archivePath "$ARCHIVE_PATH" \
    -exportPath "$EXPORT_PATH" \
    -exportOptionsPlist ExportOptions.plist

# Create ZIP
echo -e "${GREEN}Creating ZIP archive...${NC}"
cd "$BUILD_DIR"
ditto -c -k --sequesterRsrc --keepParent "$APP_NAME" "$ZIP_NAME"
cd ..

# Get file size
FILE_SIZE=$(stat -f%z "$BUILD_DIR/$ZIP_NAME")
echo -e "File size: ${YELLOW}${FILE_SIZE}${NC} bytes"

# Sign the update if tool is available
if [ -f "./sign_update" ]; then
    echo -e "${GREEN}Signing update...${NC}"
    SIGNATURE=$(./sign_update "$BUILD_DIR/$ZIP_NAME")
    echo -e "${YELLOW}${SIGNATURE}${NC}"
    echo ""
    echo -e "${YELLOW}Add this to appcast.xml:${NC}"
    echo "length=\"${FILE_SIZE}\""
    echo "sparkle:edSignature=\"$(echo $SIGNATURE | grep 'sparkle:edSignature' | cut -d'"' -f2)\""
else
    echo -e "${YELLOW}Skipping signing (sign_update not found)${NC}"
    echo "You'll need to sign manually and update appcast.xml"
fi

# Create GitHub release if gh is available
if command -v gh >/dev/null 2>&1; then
    echo ""
    read -p "Create GitHub release now? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${GREEN}Creating GitHub release...${NC}"
        gh release create "$TAG" \
            --title "${PROJECT_NAME} ${VERSION}" \
            --notes "$RELEASE_NOTES" \
            "$BUILD_DIR/$ZIP_NAME"
        
        echo -e "${GREEN}Release created successfully!${NC}"
        echo -e "View at: ${YELLOW}https://github.com/$(gh repo view --json nameWithOwner -q .nameWithOwner)/releases/tag/${TAG}${NC}"
    fi
else
    echo -e "${YELLOW}GitHub CLI not available. Create release manually:${NC}"
    echo "1. Go to https://github.com/YOUR_USERNAME/${PROJECT_NAME}/releases/new"
    echo "2. Tag: ${TAG}"
    echo "3. Title: ${PROJECT_NAME} ${VERSION}"
    echo "4. Upload: ${BUILD_DIR}/${ZIP_NAME}"
fi

echo ""
echo -e "${GREEN}=== Release build complete! ===${NC}"
echo -e "Location: ${YELLOW}${BUILD_DIR}/${ZIP_NAME}${NC}"
echo ""
echo -e "${YELLOW}Next steps:${NC}"
echo "1. Update appcast.xml with the new release entry"
echo "2. Commit and push appcast.xml to main branch"
echo "3. Test the update in the app"
