name: deploy-cloudflare

on:
  push:
    branches: [main]
  workflow_dispatch: {}

concurrency:
  group: cloudflare-deploy-${{ forgejo.ref }}
  cancel-in-progress: true

jobs:
  checks:
    if: ${{ github.server_url != 'https://codeberg.org' }}
    runs-on: codeberg-medium-lazy
    steps:
      - name: Fetch Source (no git required)
        env:
          GITHUB_TOKEN: ${{ github.token }}
        shell: bash
        run: |
          set -euo pipefail
          if [[ -z "${GITHUB_TOKEN:-}" ]]; then
            echo "error: missing github.token"
            exit 2
          fi
          if ! command -v curl >/dev/null 2>&1; then
            echo "error: curl is required"
            exit 2
          fi
          if ! command -v tar >/dev/null 2>&1; then
            echo "error: tar is required"
            exit 2
          fi
          if [[ -z "${GITHUB_SHA:-}" ]]; then
            echo "error: missing GITHUB_SHA"
            exit 2
          fi
          if [[ -z "${GITHUB_SERVER_URL:-}" ]]; then
            echo "error: missing GITHUB_SERVER_URL"
            exit 2
          fi
          if [[ -z "${GITHUB_REPOSITORY:-}" ]]; then
            echo "error: missing GITHUB_REPOSITORY"
            exit 2
          fi

          rm -rf .repo
          mkdir -p .repo

          curl -fsSL -H "Authorization: token ${GITHUB_TOKEN}" \
            "${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}/archive/${GITHUB_SHA}.tar.gz?rev=${GITHUB_SHA}" \
            -o .repo/src.tgz
          tar -xzf .repo/src.tgz -C .repo --strip-components=1
          rm -f .repo/src.tgz

      - name: Bootstrap Rust + web build tools
        shell: bash
        run: |
          set -euo pipefail
          cd .repo
          install -d -m 755 "$HOME/.local/bin"
          echo "PATH=$HOME/.local/bin:$PATH" >> "$GITHUB_ENV"
          export PATH="$HOME/.local/bin:$PATH"

          if ! command -v curl >/dev/null 2>&1; then
            echo "error: curl is required"
            exit 2
          fi

          if ! command -v cargo >/dev/null 2>&1; then
            curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal
            . "$HOME/.cargo/env"
          elif [[ -f "$HOME/.cargo/env" ]]; then
            . "$HOME/.cargo/env"
          fi
          rustup target add wasm32-unknown-unknown

          if ! command -v trunk >/dev/null 2>&1; then
            trunk_version="0.21.14"
            arch="$(uname -m)"
            case "${arch}" in
              x86_64|amd64) trunk_target="x86_64-unknown-linux-gnu" ;;
              aarch64|arm64) trunk_target="aarch64-unknown-linux-gnu" ;;
              *)
                echo "error: unsupported runner arch for trunk prebuilt binary: ${arch}"
                exit 2
                ;;
            esac
            curl -fsSL "https://github.com/trunk-rs/trunk/releases/download/v${trunk_version}/trunk-${trunk_target}.tar.gz" \
              | tar -xz -C "$HOME/.local/bin" trunk
          fi

      - name: ECP lint
        shell: bash
        run: |
          set -euo pipefail
          cd .repo
          bash ./scripts/ecp-lint.sh

      - name: Rust tests (core subset)
        shell: bash
        run: |
          set -euo pipefail
          cd .repo
          if [[ -f "$HOME/.cargo/env" ]]; then
            . "$HOME/.cargo/env"
          fi
          cargo test -p ec-core -p ec-crypto -p ec-moq -p ec-iroh -p ec-linux-iptv

      - name: Build site (web)
        shell: bash
        run: |
          set -euo pipefail
          cd .repo
          if [[ -f "$HOME/.cargo/env" ]]; then
            . "$HOME/.cargo/env"
          fi
          cd apps/web
          env -u NO_COLOR trunk build --release --public-url /

  deploy:
    if: ${{ github.server_url != 'https://codeberg.org' }}
    needs: checks
    runs-on: codeberg-medium-lazy
    steps:
      - name: Fetch Source (no git required)
        env:
          GITHUB_TOKEN: ${{ github.token }}
        shell: bash
        run: |
          set -euo pipefail
          if [[ -z "${GITHUB_TOKEN:-}" ]]; then
            echo "error: missing github.token"
            exit 2
          fi
          if ! command -v curl >/dev/null 2>&1; then
            echo "error: curl is required"
            exit 2
          fi
          if ! command -v tar >/dev/null 2>&1; then
            echo "error: tar is required"
            exit 2
          fi
          if [[ -z "${GITHUB_SHA:-}" ]]; then
            echo "error: missing GITHUB_SHA"
            exit 2
          fi
          if [[ -z "${GITHUB_SERVER_URL:-}" ]]; then
            echo "error: missing GITHUB_SERVER_URL"
            exit 2
          fi
          if [[ -z "${GITHUB_REPOSITORY:-}" ]]; then
            echo "error: missing GITHUB_REPOSITORY"
            exit 2
          fi

          rm -rf .repo
          mkdir -p .repo

          # Use the authenticated API archive endpoint (works for private repos).
          curl -fsSL -H "Authorization: token ${GITHUB_TOKEN}" \
            "${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}/archive/${GITHUB_SHA}.tar.gz?rev=${GITHUB_SHA}" \
            -o .repo/src.tgz
          tar -xzf .repo/src.tgz -C .repo --strip-components=1
          rm -f .repo/src.tgz

      - name: Bootstrap runner deps
        shell: bash
        run: |
          set -euo pipefail
          cd .repo
          install -d -m 755 "$HOME/.local/bin"
          echo "PATH=$HOME/.local/bin:$PATH" >> "$GITHUB_ENV"
          export PATH="$HOME/.local/bin:$PATH"

          if ! command -v curl >/dev/null 2>&1; then
            echo "error: curl is required"
            exit 2
          fi

          if ! command -v age >/dev/null 2>&1; then
            age_version="1.2.1"
            arch="$(uname -m)"
            case "${arch}" in
              x86_64|amd64) age_arch="amd64" ;;
              aarch64|arm64) age_arch="arm64" ;;
              *)
                echo "error: unsupported runner arch for age prebuilt binary: ${arch}"
                exit 2
                ;;
            esac
            curl -fsSL "https://github.com/FiloSottile/age/releases/download/v${age_version}/age-v${age_version}-linux-${age_arch}.tar.gz" \
              | tar -xz -C "$HOME/.local/bin" --strip-components=1 age/age age/age-keygen
          fi

          required_node_major=20
          node_major=0
          if command -v node >/dev/null 2>&1; then
            node_major="$(node -p 'parseInt(process.versions.node.split(\".\")[0], 10)' || echo 0)"
          fi
          if [[ "${node_major}" -lt "${required_node_major}" ]]; then
            node_version="22.16.0"
            arch="$(uname -m)"
            case "${arch}" in
              x86_64|amd64) node_arch="x64" ;;
              aarch64|arm64) node_arch="arm64" ;;
              *)
                echo "error: unsupported runner arch for node prebuilt binary: ${arch}"
                exit 2
                ;;
            esac
            node_dist="node-v${node_version}-linux-${node_arch}"
            curl -fsSL "https://nodejs.org/dist/v${node_version}/${node_dist}.tar.gz" | tar -xz -C "$HOME/.local"
            ln -sf "$HOME/.local/${node_dist}/bin/node" "$HOME/.local/bin/node"
            ln -sf "$HOME/.local/${node_dist}/bin/npm" "$HOME/.local/bin/npm"
            ln -sf "$HOME/.local/${node_dist}/bin/npx" "$HOME/.local/bin/npx"
            ln -sf "$HOME/.local/${node_dist}/bin/corepack" "$HOME/.local/bin/corepack" || true
          fi
          node --version
          npm --version

      - name: CI Breadcrumb (bootstrap ok)
        env:
          GITHUB_TOKEN: ${{ github.token }}
        shell: bash
        run: |
          set -euo pipefail
          cd .repo
          curl -fsSL -X POST -H "Authorization: token ${GITHUB_TOKEN}" \
            -H "content-type: application/json" \
            "${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}/statuses/${GITHUB_SHA}" \
            -d '{"context":"deploy-cloudflare/breadcrumb","state":"pending","description":"bootstrap ok"}' >/dev/null

      - name: Configure CI Age identity
        env:
          AGE_FORGE_SSH_KEY: ${{ secrets.AGE_FORGE_SSH_KEY }}
          GITHUB_TOKEN: ${{ github.token }}
        shell: bash
        run: |
          set -euo pipefail
          cd .repo
          if [[ -z "${AGE_FORGE_SSH_KEY:-}" ]]; then
            echo "error: missing Actions secret AGE_FORGE_SSH_KEY"
            exit 2
          fi
          install -d -m 700 "$HOME/.ssh"
          if [[ "${AGE_FORGE_SSH_KEY}" == "-----BEGIN OPENSSH PRIVATE KEY-----"* ]]; then
            printf '%s\n' "${AGE_FORGE_SSH_KEY}" > "$HOME/.ssh/age_forge_ed25519"
          else
            printf '%s' "${AGE_FORGE_SSH_KEY}" | base64 -d > "$HOME/.ssh/age_forge_ed25519"
          fi
          chmod 600 "$HOME/.ssh/age_forge_ed25519"

          curl -fsSL -X POST -H "Authorization: token ${GITHUB_TOKEN}" \
            -H "content-type: application/json" \
            "${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}/statuses/${GITHUB_SHA}" \
            -d '{"context":"deploy-cloudflare/breadcrumb","state":"pending","description":"age key ok"}' >/dev/null

      - name: Decrypt CI secrets from repo
        env:
          GITHUB_TOKEN: ${{ github.token }}
        shell: bash
        run: |
          set -euo pipefail
          cd .repo
          key_file="$HOME/.ssh/age_forge_ed25519"
          secret_file="secrets/cloudflare-api-token.age"
          if [[ ! -f "$secret_file" ]]; then
            echo "error: missing ${secret_file}"
            exit 2
          fi
          CLOUDFLARE_API_TOKEN="$(age -d -i "$key_file" "$secret_file")"
          if [[ -z "${CLOUDFLARE_API_TOKEN}" ]]; then
            echo "error: decrypted CLOUDFLARE_API_TOKEN is empty"
            exit 2
          fi
          echo "::add-mask::${CLOUDFLARE_API_TOKEN}"
          echo "CLOUDFLARE_API_TOKEN=${CLOUDFLARE_API_TOKEN}" >> "$GITHUB_ENV"

          curl -fsSL -X POST -H "Authorization: token ${GITHUB_TOKEN}" \
            -H "content-type: application/json" \
            "${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}/statuses/${GITHUB_SHA}" \
            -d '{"context":"deploy-cloudflare/breadcrumb","state":"pending","description":"decrypt ok"}' >/dev/null

      - name: Build site (web)
        env:
          GITHUB_TOKEN: ${{ github.token }}
        shell: bash
        run: |
          set -euo pipefail
          cd .repo
          install -d -m 755 "$HOME/.local/bin"
          export PATH="$HOME/.local/bin:$PATH"
          if ! command -v cargo >/dev/null 2>&1; then
            curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal
            . "$HOME/.cargo/env"
          elif [[ -f "$HOME/.cargo/env" ]]; then
            . "$HOME/.cargo/env"
          fi
          rustup target add wasm32-unknown-unknown
          if ! command -v trunk >/dev/null 2>&1; then
            trunk_version="0.21.14"
            arch="$(uname -m)"
            case "${arch}" in
              x86_64|amd64) trunk_target="x86_64-unknown-linux-gnu" ;;
              aarch64|arm64) trunk_target="aarch64-unknown-linux-gnu" ;;
              *)
                echo "error: unsupported runner arch for trunk prebuilt binary: ${arch}"
                exit 2
                ;;
            esac
            curl -fsSL "https://github.com/trunk-rs/trunk/releases/download/v${trunk_version}/trunk-${trunk_target}.tar.gz" \
              | tar -xz -C "$HOME/.local/bin" trunk
          fi

          cd apps/web
          trunk build --release --public-url /

          curl -fsSL -X POST -H "Authorization: token ${GITHUB_TOKEN}" \
            -H "content-type: application/json" \
            "${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}/statuses/${GITHUB_SHA}" \
            -d '{"context":"deploy-cloudflare/breadcrumb","state":"pending","description":"build ok"}' >/dev/null

      - name: Deploy worker
        env:
          GITHUB_TOKEN: ${{ github.token }}
        shell: bash
        run: |
          set -euo pipefail
          cd .repo
          cd deploy/cloudflare-worker
          npm ci
          npx wrangler deploy

          curl -fsSL -X POST -H "Authorization: token ${GITHUB_TOKEN}" \
            -H "content-type: application/json" \
            "${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}/statuses/${GITHUB_SHA}" \
            -d '{"context":"deploy-cloudflare/breadcrumb","state":"success","description":"deploy ok"}' >/dev/null
