name: Gitea Release

on:
  workflow_call:
    inputs:
      gitea_ref_name:
        description: 'Gitea ref name'
        required: true
        type: string
      gitea_server_url:
        description: 'Gitea server URL'
        required: true
        type: string
      gitea_repository:
        description: 'Gitea repository'
        required: true
        type: string
    secrets:
      GITEA_TOKEN:
        required: true

jobs:
  create-release:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout Repository
      uses: actions/checkout@v4

    - name: Install System Dependencies
      run: |
        sudo apt-get update
        sudo apt-get install -y python3 python3-venv build-essential curl git

    - name: Set up Python Virtual Environment
      run: |
        python3 -m venv venv
        source venv/bin/activate
        pip install --upgrade pip
        pip install platformio esptool
        
        echo "Verifying installations:"
        platformio --version
        python3 --version
        esptool.py version

    - name: Build Firmware
      run: |
        source venv/bin/activate
        echo "Building SPIFFS..."
        platformio run -t buildfs
        
        echo "Building firmware..."
        platformio run

    - name: Create Release Files
      run: |
        source venv/bin/activate
        echo "Creating release files..."
        esptool.py --chip esp32 merge_bin \
          --flash_mode dio \
          --flash_freq 40m \
          --flash_size 4MB \
          -o .pio/build/esp32dev/filaman_full.bin \
          0x1000 .pio/build/esp32dev/bootloader.bin \
          0x8000 .pio/build/esp32dev/partitions.bin \
          0x10000 .pio/build/esp32dev/firmware.bin \
          0x290000 .pio/build/esp32dev/spiffs.bin
        
        cp .pio/build/esp32dev/firmware.bin .pio/build/esp32dev/filaman_ota.bin

    - name: Read CHANGELOG.md
      id: changelog
      run: |
        VERSION=${{ inputs.gitea_ref_name }}
        CHANGELOG=$(awk "/## \\[$VERSION\\]/{p=1;print;next} /## \\[/ {p=0} p" CHANGELOG.md)
        echo "CHANGES<<EOF" >> $GITHUB_OUTPUT
        echo "$CHANGELOG" >> $GITHUB_OUTPUT
        echo "EOF" >> $GITHUB_OUTPUT
        echo "CHANGELOG CONTENT:"
        echo "$CHANGELOG"
        if [ -z "$CHANGELOG" ]; then
          echo "No changelog found for version $VERSION"
          exit 1
        fi

    - name: Create Release
      env:
        TOKEN: ${{ secrets.GITEA_TOKEN }}
        GITEA_REF_NAME: ${{ inputs.gitea_ref_name }}
        GITEA_SERVER_URL: ${{ inputs.gitea_server_url }}
        GITEA_REPOSITORY: ${{ inputs.gitea_repository }}
        CHANGELOG: ${{ steps.changelog.outputs.CHANGES }}
      run: |
        echo "Debug environment:"
        echo "GITEA_REF_NAME: ${GITEA_REF_NAME}"
        echo "GITEA_SERVER_URL: ${GITEA_SERVER_URL}"
        echo "GITEA_REPOSITORY: ${GITEA_REPOSITORY}"
        echo "CHANGELOG: ${CHANGELOG}"
        
        TAG="${GITEA_REF_NAME}"
        API_URL="${GITEA_SERVER_URL}/api/v1"
        REPO="${GITEA_REPOSITORY}"
        
        echo "Creating release for ${TAG} on ${REPO}..."
        
        # Create release
        RESPONSE=$(curl -k -s \
          -X POST \
          -H "Authorization: token ${TOKEN}" \
          -H "Content-Type: application/json" \
          -d "{\"tag_name\":\"${TAG}\",\"name\":\"Release ${TAG}\",\"body\":\"${CHANGELOG}\"}" \
          "${API_URL}/repos/${REPO}/releases")
        
        RELEASE_ID=$(echo "$RESPONSE" | grep -o '"id":[0-9]*' | cut -d':' -f2 | head -n1)
        UPLOAD_URL=$(echo "$RESPONSE" | grep -o '"upload_url":"[^"]*' | cut -d':' -f2- | tr -d '"')
        
        if [ -n "$RELEASE_ID" ]; then
          echo "Release created with ID: $RELEASE_ID"
          
          # Upload files
          for file in "filaman_full.bin" "filaman_ota.bin"; do
            echo "Uploading $file..."
            curl -k -s \
              -X POST \
              -H "Authorization: token ${TOKEN}" \
              -H "Content-Type: application/octet-stream" \
              --data-binary "@.pio/build/esp32dev/$file" \
              "${UPLOAD_URL}?name=$file"
          done
        else
          echo "Failed to create release. Response:"
          echo "$RESPONSE"
          exit 1
        fi