# Disable bearer-token auth on the prod arbo engine (irv-ml1), leaning on
# WireGuard as the access boundary. Operator decision 2026-06-13 (relayed by
# comfy-dev, confirmed in-session). Deliberately reverses ADR-0001's
# "open-auth hole closed (ENGINE_TOKEN minted)" line.
#
# GOTCHA (why .env-only is not enough): the app's `dependencies=protected`
# gate no-ops only when ENGINE_TOKEN is ABSENT from the container env. An
# empty string still gates (verified 2026-06-13: ENGINE_TOKEN="" -> /workflows
# still 401). The var is injected by TWO paths, both must be removed:
#   1. env_file: .env            -> delete the ENGINE_TOKEN line from .env
#   2. environment: - ENGINE_TOKEN=${ENGINE_TOKEN}  -> commented out in compose
# With both gone the var is unset in the container and the engine serves open,
# exactly like the dev engine on nh3-dev.
#
# Reversible: the pre-change .env (with the real token) is backed up to
# .env.pre-auth-off.bak. To re-lock: restore the ENGINE_TOKEN line in .env,
# un-comment the compose line, `compose up -d`.
#
# No sudo: lkraven owns the compose dir + .env and is in the docker group.

vars:
  dir: /opt/docker/compose/arbo

steps:
  - name: Back up prod .env (preserves the real ENGINE_TOKEN for re-enable)
    shell: cp -p {{ dir }}/.env {{ dir }}/.env.pre-auth-off.bak
    # creates: guards the FIRST backup — never clobber it on a rerun.
    creates: "{{ dir }}/.env.pre-auth-off.bak"

  - name: Remove the ENGINE_TOKEN line from .env entirely (must be ABSENT, not empty)
    shell: sed -i '/^ENGINE_TOKEN=/d' {{ dir }}/.env
    when: "grep -qE '^ENGINE_TOKEN=' {{ dir }}/.env"

  - name: Push the corrected compose (ENGINE_TOKEN injection commented out)
    upload:
      src: stacks/arbo/compose.yaml
      dest: "{{ dir }}/compose.yaml"
      mode: "0644"

  - name: Recreate the engine so ENGINE_TOKEN is absent from its env
    shell: docker compose -f {{ dir }}/compose.yaml up -d

verify:
  - name: .env no longer defines ENGINE_TOKEN
    shell: "! grep -qE '^ENGINE_TOKEN=' {{ dir }}/.env"
    changed_when: "false"

  - name: Backup still carries the original token (reversibility intact)
    shell: grep -qE '^ENGINE_TOKEN=.+' {{ dir }}/.env.pre-auth-off.bak
    changed_when: "false"

  - name: ENGINE_TOKEN is ABSENT from the running container env
    shell: "! docker exec arbo printenv ENGINE_TOKEN >/dev/null 2>&1"
    changed_when: "false"

  - name: Protected endpoint serves tokenless after warmup (auth OFF — expect HTTP 200, was 401)
    shell: |
      port=$(docker port arbo 8200/tcp 2>/dev/null | sed -n 's/.*:\([0-9]\+\)$/\1/p' | head -1)
      final=000
      for i in $(seq 1 30); do
        code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "http://localhost:${port}/workflows")
        if [ "$code" != "000" ]; then final=$code; break; fi
        sleep 2
      done
      echo "tokenless GET /workflows on :${port} -> HTTP ${final}"
      test "$final" = "200"
    changed_when: "false"
