name: Release Daytona Snapshot

on:
  workflow_call:
    inputs:
      tag:
        description: "Tag to build from (e.g., v0.11.200). Defaults to current ref."
        required: false
        type: string
      snapshot_name:
        description: "Optional explicit Daytona snapshot name"
        required: false
        type: string
      snapshot_region:
        description: "Optional Daytona region override for snapshot push"
        required: false
        type: string
  workflow_dispatch:
    inputs:
      tag:
        description: "Tag to build from (e.g., v0.11.200). Defaults to release tag/current ref."
        required: false
        type: string
      snapshot_name:
        description: "Optional explicit Daytona snapshot name"
        required: false
        type: string
      snapshot_region:
        description: "Optional Daytona region override for snapshot push"
        required: false
        type: string

permissions:
  contents: read

concurrency:
  # Reusable workflows inherit the caller's github.workflow. A recovery caller
  # already holds Release App-<tag>; use our own namespace to avoid deadlocking
  # against the parent while still serializing snapshot builds for the same tag.
  group: release-daytona-snapshot-${{ inputs.tag || github.ref_name }}
  cancel-in-progress: false

jobs:
  publish-daytona-snapshot:
    name: Build and Push Daytona Snapshot
    runs-on: blacksmith-4vcpu-ubuntu-2404
    # Render deploy secrets belong to this environment; no deployment is recorded.
    environment:
      name: den-production
      deployment: false
    outputs:
      release_tag: ${{ steps.resolve.outputs.release_tag }}
      snapshot_name: ${{ steps.resolve.outputs.snapshot_name }}
      snapshot_region: ${{ steps.resolve.outputs.snapshot_region }}
    steps:
      - name: Resolve release tag and snapshot name
        id: resolve
        shell: bash
        env:
          INPUT_TAG: ${{ inputs.tag }}
          INPUT_SNAPSHOT_NAME: ${{ inputs.snapshot_name }}
          INPUT_SNAPSHOT_REGION: ${{ inputs.snapshot_region }}
          SNAPSHOT_NAME_BASE: ${{ vars.DAYTONA_SNAPSHOT_NAME_BASE }}
          DEFAULT_SNAPSHOT_REGION: ${{ vars.DAYTONA_SNAPSHOT_REGION }}
        run: |
          set -euo pipefail

          tag="${INPUT_TAG:-}"
          if [ -z "$tag" ]; then
            tag="${GITHUB_REF_NAME}"
          fi
          if [[ "$tag" != v* ]]; then
            tag="v${tag}"
          fi
          if [[ ! "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
            echo "Invalid release tag: $tag" >&2
            exit 1
          fi

          base_name="${SNAPSHOT_NAME_BASE:-openwork}"
          if [ -n "${INPUT_SNAPSHOT_NAME:-}" ]; then
            snapshot_name="${INPUT_SNAPSHOT_NAME}"
          else
            snapshot_name="${base_name}-${tag#v}"
          fi
          snapshot_region="${INPUT_SNAPSHOT_REGION:-${DEFAULT_SNAPSHOT_REGION:-}}"

          echo "release_tag=$tag" >> "$GITHUB_OUTPUT"
          echo "snapshot_name=$snapshot_name" >> "$GITHUB_OUTPUT"
          echo "snapshot_region=$snapshot_region" >> "$GITHUB_OUTPUT"

      - name: Verify release ref is a tag
        shell: bash
        env:
          RELEASE_TAG: ${{ steps.resolve.outputs.release_tag }}
        run: |
          set -euo pipefail

          if ! git ls-remote --exit-code --tags \
            "https://github.com/${GITHUB_REPOSITORY}.git" \
            "refs/tags/${RELEASE_TAG}" >/dev/null; then
            echo "::error::Ref ${RELEASE_TAG} does not exist as a tag in ${GITHUB_REPOSITORY}."
            exit 1
          fi
          echo "Verified tag: ${RELEASE_TAG}"

      - name: Checkout release source
        uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
        with:
          fetch-depth: 0
          ref: refs/tags/${{ steps.resolve.outputs.release_tag }}

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.9.0

      - name: Install Daytona CLI
        # Pinned and checksum-verified because the CLI runs with DAYTONA_API_KEY.
        # Bump the version and SHA together (Warden MZE-XC3).
        shell: bash
        env:
          DAYTONA_CLI_VERSION: v0.190.0
          DAYTONA_CLI_SHA256: 1d3591a1ea61d801696110e1b5f3381f223a56a623a882940d0d85742862fd44
        run: |
          set -euo pipefail

          mkdir -p "$HOME/.local/bin"
          curl -fL "https://github.com/daytonaio/daytona/releases/download/${DAYTONA_CLI_VERSION}/daytona-linux-amd64" \
            -o "$HOME/.local/bin/daytona"
          printf '%s  %s\n' "$DAYTONA_CLI_SHA256" "$HOME/.local/bin/daytona" | sha256sum -c -
          chmod +x "$HOME/.local/bin/daytona"
          echo "$HOME/.local/bin" >> "$GITHUB_PATH"
          export PATH="$HOME/.local/bin:$PATH"

          daytona version

      - name: Build and push snapshot
        id: publish
        shell: bash
        env:
          DAYTONA_API_KEY: ${{ secrets.DAYTONA_API_KEY }}
          DAYTONA_API_URL: ${{ vars.DAYTONA_API_URL }}
          DAYTONA_TARGET: ${{ vars.DAYTONA_TARGET }}
          DAYTONA_SNAPSHOT_REGION: ${{ steps.resolve.outputs.snapshot_region }}
          DAYTONA_SNAPSHOT_NAME: ${{ steps.resolve.outputs.snapshot_name }}
        run: |
          set -euo pipefail

          if [ -z "${DAYTONA_API_KEY:-}" ]; then
            echo "Missing required secret: DAYTONA_API_KEY" >&2
            exit 1
          fi

          export DAYTONA_CONFIG_DIR="$RUNNER_TEMP/daytona"
          mkdir -p "$DAYTONA_CONFIG_DIR"
          daytona login --api-key "$DAYTONA_API_KEY"

          echo "Publishing Daytona snapshot: ${DAYTONA_SNAPSHOT_NAME}"
          ./scripts/create-daytona-openwork-snapshot.sh "${DAYTONA_SNAPSHOT_NAME}"

      - name: Note skipped release pin
        if: vars.DAYTONA_PIN_CHANNEL == 'dev'
        shell: bash
        run: |
          echo "::notice::web engine channel is 'dev'; release snapshot pin skipped (set DAYTONA_PIN_CHANNEL=release to restore release pinning)"
          echo "Skipped release snapshot pin: web engine channel is \`dev\`. Set \`DAYTONA_PIN_CHANNEL=release\` to restore release pinning." >> "$GITHUB_STEP_SUMMARY"

      - name: Checkout snapshot pin automation
        if: steps.publish.outcome == 'success' && vars.DAYTONA_CLOUD_ENV_GROUP_ID != '' && vars.DAYTONA_PIN_CHANNEL != 'dev'
        uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
        with:
          ref: ${{ github.sha }}
          path: .snapshot-pin-automation
          sparse-checkout: scripts/update-daytona-snapshot-pin.mjs
          sparse-checkout-cone-mode: false

      - name: Update production snapshot pin
        id: pin
        if: steps.publish.outcome == 'success' && vars.DAYTONA_PIN_CHANNEL != 'dev'
        shell: bash
        env:
          DAYTONA_CLOUD_ENV_GROUP_ID: ${{ vars.DAYTONA_CLOUD_ENV_GROUP_ID }}
          DAYTONA_SNAPSHOT_NAME: ${{ steps.resolve.outputs.snapshot_name }}
          RENDER_API_KEY: ${{ secrets.RENDER_API_KEY }}
        run: |
          set -euo pipefail

          if [ -z "${DAYTONA_CLOUD_ENV_GROUP_ID:-}" ]; then
            echo "::notice::DAYTONA_CLOUD_ENV_GROUP_ID is not configured; skipping production snapshot pin update."
            {
              echo "### Daytona snapshot pin"
              echo
              echo "Skipped: repository variable \`DAYTONA_CLOUD_ENV_GROUP_ID\` is not configured."
            } >> "$GITHUB_STEP_SUMMARY"
            exit 0
          fi
          if [ -z "${RENDER_API_KEY:-}" ]; then
            echo "::error::Missing required secret: RENDER_API_KEY"
            exit 1
          fi

          result="$(node .snapshot-pin-automation/scripts/update-daytona-snapshot-pin.mjs \
            --env-group-id "$DAYTONA_CLOUD_ENV_GROUP_ID" \
            --snapshot "$DAYTONA_SNAPSHOT_NAME")"
          echo "$result"
          {
            echo "### Daytona snapshot pin"
            echo
            echo "$result"
          } >> "$GITHUB_STEP_SUMMARY"
          changed=false
          case "$result" in
            updated:*) changed=true ;;
          esac
          echo "changed=$changed" >> "$GITHUB_OUTPUT"

      - name: Redeploy den-api so the new pin takes effect
        # Render does not redeploy services when an env group value changes, so
        # den-api keeps serving the previous DAYTONA_SNAPSHOT until it redeploys.
        # Without this the pin moves but `latestVersion` stays stale and no
        # sandbox ever recycles - observed for real on v0.18.11.
        # Gated on the pin actually moving, so unchanged re-runs and the
        # nightly backstop no longer redeploy production for a no-op.
        if: steps.pin.outcome == 'success' && steps.pin.outputs.changed == 'true' && vars.DAYTONA_PIN_CHANNEL != 'dev'
        shell: bash
        env:
          RENDER_API_KEY: ${{ secrets.RENDER_API_KEY }}
          RENDER_DEN_SERVICE_ID: ${{ secrets.RENDER_DEN_CONTROL_PLANE_SERVICE_ID }}
        run: |
          set -euo pipefail

          if [ -z "${RENDER_DEN_SERVICE_ID:-}" ] || [ -z "${RENDER_API_KEY:-}" ]; then
            echo "::notice::Render den-api credentials unavailable; skipping redeploy. The pin will take effect on the next den-api deploy."
            exit 0
          fi

          response="$(curl -s -w '\n%{http_code}' -X POST \
            "https://api.render.com/v1/services/${RENDER_DEN_SERVICE_ID}/deploys" \
            -H "Authorization: Bearer $RENDER_API_KEY" \
            -H "Content-Type: application/json" \
            -d '{}')"
          code="$(printf '%s' "$response" | tail -1)"
          body="$(printf '%s' "$response" | sed '$d')"
          if [ "$code" -ge 400 ]; then
            echo "::error::POST /deploys returned HTTP $code: $body"
            exit 1
          fi

          {
            echo
            echo "Triggered a den-api deploy so the new pin takes effect."
          } >> "$GITHUB_STEP_SUMMARY"

      # Tagged release snapshots accumulate forever without this: nothing else
      # deletes them and the dev pruner is scoped to `<base>-dev-*` names only.
      # Keep the just-published snapshot, the current production pin, the 20
      # newest releases, in-flight builds, and anything an active sandbox still
      # references. Checked out at the workflow SHA (not the release tag) so
      # older tags without release-channel support still get pruned.
      - name: Checkout snapshot prune automation
        if: steps.publish.outcome == 'success'
        uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
        with:
          ref: ${{ github.sha }}
          path: .snapshot-prune-automation
          sparse-checkout: |
            scripts/prune-daytona-dev-snapshots.mjs
            scripts/update-daytona-snapshot-pin.mjs
          sparse-checkout-cone-mode: false

      - name: Prune old release snapshots
        if: steps.publish.outcome == 'success'
        shell: bash
        env:
          DAYTONA_API_KEY: ${{ secrets.DAYTONA_API_KEY }}
          DAYTONA_API_URL: ${{ vars.DAYTONA_API_URL }}
          DAYTONA_CLOUD_ENV_GROUP_ID: ${{ vars.DAYTONA_CLOUD_ENV_GROUP_ID }}
          DAYTONA_PIN_CHANNEL: ${{ vars.DAYTONA_PIN_CHANNEL }}
          DAYTONA_SNAPSHOT_NAME_BASE: ${{ vars.DAYTONA_SNAPSHOT_NAME_BASE }}
          DAYTONA_SNAPSHOT_NAME: ${{ steps.resolve.outputs.snapshot_name }}
          RENDER_API_KEY: ${{ secrets.RENDER_API_KEY }}
        run: |
          set -euo pipefail

          keep_args=(--keep "$DAYTONA_SNAPSHOT_NAME")
          current_pin=""
          if [ -n "${DAYTONA_CLOUD_ENV_GROUP_ID:-}" ] && [ -n "${RENDER_API_KEY:-}" ]; then
            current_pin="$(node .snapshot-prune-automation/scripts/update-daytona-snapshot-pin.mjs \
              --env-group-id "$DAYTONA_CLOUD_ENV_GROUP_ID" --read || true)"
          fi
          if [ -n "$current_pin" ]; then
            keep_args+=(--keep "$current_pin")
          elif [ "${DAYTONA_PIN_CHANNEL:-}" != "dev" ]; then
            # The production pin may be a release snapshot on this channel;
            # never prune blind to it.
            echo "::warning::release snapshot prune skipped: current production pin unknown while the engine channel pins releases"
            echo "release snapshot prune skipped: current production pin unknown" >> "$GITHUB_STEP_SUMMARY"
            exit 0
          fi

          result="$(node .snapshot-prune-automation/scripts/prune-daytona-dev-snapshots.mjs \
            ${DAYTONA_API_URL:+--api-url "$DAYTONA_API_URL"} \
            --channel release \
            --name-base "${DAYTONA_SNAPSHOT_NAME_BASE:-openwork}" \
            "${keep_args[@]}" \
            --keep-count 20)"
          echo "$result"
          {
            echo "### Daytona release snapshot prune"
            echo
            echo '```'
            echo "$result"
            echo '```'
          } >> "$GITHUB_STEP_SUMMARY"