#!/usr/bin/env bash
#
# Land the current worktree's branch on its project's main.
#
#   land [--seen <sha>] [--verify-only] [--dry-run] [--allow-unverified]
#        [--targets sim,web|+wasm|-apk|all] [--deploy target,target]
#        [--hold-deploy "why"] [--finish]
#
# One landing at a time, in turn (`midas land take`); fetch; the project's
# pre-land check; rebase onto main, stopping first when main moved under files
# this branch changes; the project's gate on a build node; push the branch and
# fast-forward main; give the turn back; deploy if asked. The targets the hub
# deploys after landings (`midas deploy` lists them) need no --deploy: it
# deploys them itself, in batches — those this landing changes and does not
# leave to later: `midas land targets` proposes them, --targets changes the
# proposal (as `midas land targets --pick`). --hold-deploy holds those until a person
# deploys or releases (`midas deploy --release`): on main, not live. --finish
# finishes this worktree's hub session once what it landed is live (the answer
# "Land it and finish"). A session working in several projects lands each from
# its own worktree, the one depended on first, with --finish on every one: it
# finishes once all of them are live.
#
# What is the project's comes from the hub (`midas project`, hub.conf
# `projects`): the gate, which nodes may run it, the pre-land check, and the
# name of main. Installed by midas into ~/.claude/skills (`midas claude
# install`); a project that needs its own landing keeps a `finish-branch` skill
# in its repository, which Claude Code prefers to this one.
#
# Exit 0 landed (or, with --verify-only/--dry-run, would have); 1 refused or
# failed; 4 stopped to read what moved on main (re-run with --seen).

set -uo pipefail

argv=("$@")
seen=""
dry_run=""
verify_only=""
allow_unverified=""
deploy=""
targets=""
hold_deploy=""
finish=""
while [ $# -gt 0 ]; do
    case "$1" in
        --seen)              seen="$2"; shift 2 ;;
        --dry-run)           dry_run=1; shift ;;
        --verify-only)       verify_only=1; shift ;;
        --allow-unverified)  allow_unverified=1; shift ;;
        --deploy)            deploy="$2"; shift 2 ;;
        --targets)           targets="$2"; shift 2 ;;
        --hold-deploy)       hold_deploy="$2"; shift 2 ;;
        --finish)            finish=1; shift ;;
        -h|--help) sed -n '2,34p' "$0"; exit 0 ;;
        *) echo "unknown argument: $1" >&2; exit 2 ;;
    esac
done

command -v midas >/dev/null || { echo "no midas on the PATH: landing needs the hub" >&2; exit 1; }
root=$(git rev-parse --show-toplevel) || exit 1
cd "$root" || exit 1
gitdir=$(git rev-parse --git-dir)

# ── The project ──────────────────────────────────────────────────────────────
project=$(midas project --get repo) || exit 1
main=$(midas project --get main) || exit 1
gate=$(midas project --get gate) || exit 1
gate_nodes=$(midas project --get gate_nodes) || exit 1
# A repository the hub hosts moves main only for the session holding the turn
# (src/hosted.rs): the push says whose landing it is.
push_opts=()
[ "$(midas project --get host 2>/dev/null)" = midas ] && push_opts=(-o "midas-owner=$(midas whoami)")
pre_land=$(midas project --get pre_land) || exit 1
if [ -z "$gate" ] && [ -z "$allow_unverified" ]; then
    echo "refusing: $project has no gate at the hub (hub.conf \`projects\`, docs/hub.md)." >&2
    echo "Ask the person to set one; --allow-unverified lands without, on their say." >&2
    exit 1
fi

# ── Which branch ─────────────────────────────────────────────────────────────
branch=$(git rev-parse --abbrev-ref HEAD)
[ "$branch" != "HEAD" ] || {
    echo "refusing: detached HEAD — check out a branch first" >&2; exit 1; }
[ "$branch" != "$main" ] || { echo "refusing: this worktree is on $main itself" >&2; exit 1; }
echo "project  $project"
echo "branch   $branch → $main"

# What is gated is what lands: nothing uncommitted may ride along or be left out.
if [ -n "$(git status --porcelain)" ]; then
    echo "refusing: uncommitted changes — commit them first" >&2
    git status --short >&2
    exit 1
fi

# ── The turn to land ─────────────────────────────────────────────────────────
# Taken before the fetch, so the main the gate tests is the main this pushes
# onto. A re-run of this script by itself (below) already holds it, and asking
# again only renews it. --verify-only and --dry-run push nothing and wait for
# nobody.
step() { :; }
if [ -z "$verify_only$dry_run" ]; then
    # Somebody lands before this one, and its gate may need the node this
    # worktree holds: holding it while waiting for our turn stopped both
    # landings (2026-10-23, the vps's only node; nothing said so). Given back
    # here; the gate takes a node of its own when the turn comes.
    held=$(midas mine 2>/dev/null | jq -r --arg g "$gate_nodes" \
        'select($g == "" or $g == "any" or .machine == $g or .id == $g or ($g == "gpu" and .gpu == true)) | .id // empty' 2>/dev/null)
    if [ -n "$held" ] && ! midas land status 2>/dev/null | grep -q "nobody is landing"; then
        echo "==> another landing goes first, and its gate may need $held: giving it back"
        midas release >/dev/null 2>&1 || true
    fi
    echo "==> taking the turn to land (midas land status shows the line)"
    midas land take --purpose "landing $branch" || {
        echo "no turn to land came — run it again later" >&2; exit 1; }
    land_outcome="abandoned"; land_sha=""
    # Every minute while this script lives; `kill -0 $$` ends it when the
    # script is killed outright, so the turn lapses at the hub instead of being
    # kept by an orphan.
    ( while sleep 60 && kill -0 $$ 2>/dev/null; do midas land renew >/dev/null 2>&1; done ) &
    renewer=$!
    disown "$renewer"
    trap 'kill "$renewer" 2>/dev/null; midas land release --outcome "$land_outcome" ${land_sha:+--sha "$land_sha"} >/dev/null 2>&1' EXIT
    step() { midas land renew --step "$1" >/dev/null 2>&1 || true; }
fi

step "rebasing onto $main"
echo "==> fetching origin/$main"
git fetch --quiet origin "$main" || { echo "could not fetch origin" >&2; exit 1; }
upstream="origin/$main"
if [ "$(git rev-parse HEAD)" = "$(git rev-parse "$upstream")" ]; then
    echo "refusing: HEAD is already exactly $upstream — nothing to land" >&2
    exit 1
fi

# ── The project's pre-land check ─────────────────────────────────────────────
# Before the rebase: what it looks for (two branches claiming one number) is
# exactly what a rebase lets through without a conflict.
if [ -n "$pre_land" ]; then
    echo "==> the pre-land check: $pre_land"
    if ! MIDAS_BASE="$upstream" sh -c "$pre_land"; then
        land_outcome="failed"
        echo "" >&2
        echo "not landing: the pre-land check refused it. Fix it, commit, and re-run." >&2
        exit 1
    fi
fi

# ── What moved on main, read before rebasing onto it ─────────────────────────
# A rebase that applies clean can still be wrong: main took a number, renamed a
# function, or changed the meaning of a file this branch also changes, and git
# sees none of it. So when main changed a file this branch changes too, this
# stops, names those commits, and goes on only once they have been read — the
# re-run says so with --seen and the main it read.
if ! git merge-base --is-ancestor "$upstream" HEAD; then
    mb=$(git merge-base HEAD "$upstream")
    now=$(git rev-parse "$upstream")
    echo "==> $main has moved since this branch left it:"
    git log --format='    %h %s' "$mb..$upstream"
    ours=$(git diff --name-only "$mb" HEAD | sort)
    theirs=$(git diff --name-only "$mb" "$upstream" | sort)
    both=$(printf '%s\n' "$ours" | grep -Fxf <(printf '%s\n' "$theirs") || true)
    read_it=""
    case "$now" in "$seen"?*) [ ${#seen} -ge 7 ] && read_it=1 ;; esac
    [ "$seen" = "$now" ] && read_it=1
    if [ -n "$both" ] && [ -z "$read_it" ]; then
        echo "" >&2
        echo "$main changed files this branch changes too:" >&2
        printf '    %s\n' $both >&2
        echo "" >&2
        echo "Read what it did to them before landing on it:" >&2
        echo "    git log -p $mb..$upstream -- $(printf '%s ' $both)" >&2
        echo "then re-run with --seen ${now:0:12}. Nothing was rebased; the turn is given back." >&2
        land_outcome="stopped to read $main"
        exit 4
    fi
    echo "==> rebasing onto ${now:0:8}"
    if ! git rebase "$upstream"; then
        land_outcome="conflict"
        echo "" >&2
        echo "the rebase conflicts with $main — resolve it, then re-run:" >&2
        echo "    git status; git rebase --continue" >&2
        echo "if $main already has the same change, that is 'git rebase --skip'," >&2
        echo "not a merge of two versions of one change." >&2
        exit 1
    fi
fi

# ── Handover sweeps ──────────────────────────────────────────────────────────
# The handover skill's `wip:` commit holds what a session left uncommitted. It
# is a sweep, not a change, and nothing after this point would stop it.
wip=$(git log --format='%h %s' "$upstream..HEAD" | grep -E '^[0-9a-f]+ wip:' || true)
if [ -n "$wip" ]; then
    echo "refusing: the branch still carries wip commits — fold them into real commits first:" >&2
    printf '    %s\n' "$wip" >&2
    echo "(the handover skill says how)" >&2
    exit 1
fi

sha=$(git rev-parse HEAD)
echo "head     $sha"
echo "landing  $(git rev-list --count "HEAD" "^$upstream") commit(s)"

# ── The gate ─────────────────────────────────────────────────────────────────
# On a build node, never here. The receipt is keyed on the sha, so a rebase
# after a pass makes it stale — a tree replayed onto different code has not
# been gated.
receipt="$gitdir/midas-verified"
verified=""
[ -f "$receipt" ] && verified=$(sed -n 's/^sha=//p' "$receipt" | head -1)
if [ "$verified" = "$sha" ]; then
    echo "==> already gated at ${sha:0:8} on $(sed -n 's/^node=//p' "$receipt")"
elif [ -n "$allow_unverified" ]; then
    # Only ever on the person's word, and loud in the transcript.
    echo "==> --allow-unverified: landing without running the gate"
else
    step "gating ${sha:0:8}"
    # The node this worktree holds, if it holds one and the project lets it
    # gate: releasing it to take another only buys a wait. `midas mine` prints
    # the node as JSON; its machine or its id must be what gate_nodes names,
    # and "any" (the default) names every node. Until 2026-10-30 "any" matched
    # none, so a session holding a Mac was gated on whichever node was fastest.
    node=$(midas mine 2>/dev/null | jq -r --arg g "$gate_nodes" \
        'select($g == "" or $g == "any" or .machine == $g or .id == $g or ($g == "gpu" and .gpu == true)) | .id // empty' 2>/dev/null)
    # The worktree's session: a worktree in a session's folder (one per project) is that session's.
    if [ -f "$(dirname "$root")/.midas-session" ]; then whose=$(basename "$(dirname "$root")"); else whose=$(basename "$root"); fi
    gate_owner="gate-$whose"
    # Unless a free node is faster at the gate: a session holding the CPU node
    # gated there while a Mac sat free, four times slower (40% of Cartopolis
    # gates, 2026-10-28 to 11-27). The node held stays the session's.
    if [ -n "$node" ] && faster=$(midas faster --than "$node" "${gate_nodes:-any}" --fastest-for "$gate" --owner "$gate_owner" 2>/dev/null); then
        echo "==> $faster is free and faster at the gate than $node, which this worktree holds: gating there"
        node=""
    fi
    if [ -n "$node" ]; then
        echo "==> gating on $node (this worktree holds it): $gate"
    else
        node=$(midas take "$gate_nodes" --fastest-for "$gate" --owner "$gate_owner" --wait 3600 \
            --purpose "landing gate for $branch") || {
            land_outcome="failed"; echo "no node came free in an hour; not gating" >&2; exit 1; }
        trap 'kill "${renewer:-}" 2>/dev/null; midas release --owner "$gate_owner" >/dev/null 2>&1; [ -z "${renewer:-}" ] || midas land release --outcome "$land_outcome" ${land_sha:+--sha "$land_sha"} >/dev/null 2>&1' EXIT
        echo "==> gating on $node: $gate"
    fi
    mb=$(git merge-base HEAD "$upstream")
    # The node follows this worktree: the ssh sends it the rebased head first.
    ssh -o BatchMode=yes "$node" "export MIDAS_BASE=$mb; $gate"
    status=$?
    there=$(ssh -o BatchMode=yes "$node" 'git rev-parse HEAD' 2>/dev/null)
    if [ "$status" -ne 0 ]; then
        land_outcome="failed"
        echo "" >&2
        echo "not landing: the gate is red on $node. Fix it and re-run." >&2
        exit 1
    fi
    if [ "$there" != "$sha" ]; then
        land_outcome="failed"
        echo "not landing: $node gated ${there:0:8}, not ${sha:0:8}" >&2
        exit 1
    fi
    printf 'sha=%s\nnode=%s\nat=%s\n' "$sha" "$node" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$receipt"
    # And at the hub, which `midas deploy` asks before it publishes a commit.
    midas verified --sha "$sha" --node "$node" --steps "$gate" >/dev/null 2>&1 \
        || echo "note: the hub did not take the receipt; \`midas deploy\` will ask for --unverified" >&2
    echo "    green on $node"
fi

[ -n "$verify_only" ] && { echo "--verify-only: stopping before the push"; exit 0; }
[ -n "$dry_run" ] && { echo "(dry run: would push $branch and fast-forward $main to ${sha:0:8})"; exit 0; }

# ── Land it ──────────────────────────────────────────────────────────────────
# Held first: the hub deploys what lands within a minute once nobody else is in
# line, and a hold put after the push could come too late. A landing that does
# not happen gives its hold back.
held_here=""
if [ -n "$hold_deploy" ]; then
    midas deploy --hold "$hold_deploy" >/dev/null || { echo "could not hold the deploys; not landing" >&2; exit 1; }
    held_here=1
    echo "==> deploys after landings held: $hold_deploy"
fi
unhold() { [ -z "$held_here" ] || midas deploy --release >/dev/null 2>&1 || true; }

# Which targets this landing builds, told to the hub before main moves, so the
# planner never sees the landing without it: by default every changed one that
# is not optional; --targets as the person answered "Shall it land?". A hub
# that did not take it builds the default.
echo "==> what this landing builds"
midas land targets --base "$upstream" --record ${targets:+--pick "$targets"} | sed 's/^/    /' \
    || echo "note: the hub did not take the targets; it builds the default" >&2

# Landed without the gate, on the person's word: said at the hub as such, so
# the deploys after landings go out (with no receipt they never did, and the
# session waited for "live" for ever, s530 on 2026-10-31).
if [ -n "$allow_unverified" ] && [ "$verified" != "$sha" ]; then
    midas verified --sha "$sha" --scope "ungated: landed without the gate on the person's word" --steps "(none)" >/dev/null 2>&1 \
        || echo "note: the hub did not take the ungated record; deploy by hand: midas deploy <target> --sha $sha --unverified \"why\"" >&2
fi

# The branch goes up too and stays, so what landed can be found by the name the
# session worked under. Plain first, --force-with-lease after a rebase.
echo "==> pushing $branch"
if ! git push --quiet origin "HEAD:refs/heads/$branch" 2>/dev/null; then
    git push --force-with-lease --quiet origin "HEAD:refs/heads/$branch" || {
        unhold; echo "could not push the branch" >&2; exit 1; }
    echo "    (force-with-lease, after the rebase)"
fi

# Never forced: a rejection means main moved after the fetch, which with the
# turn held is only a push that did not come through the queue. Go round again
# keeping the turn — `exec` runs no EXIT trap, so nothing is released.
echo "==> fast-forwarding $main to ${sha:0:8}"
step "pushing ${sha:0:8}"
if ! git push --quiet ${push_opts[@]+"${push_opts[@]}"} origin "HEAD:refs/heads/$main"; then
    attempt=${MIDAS_LAND_ATTEMPT:-1}
    if [ -n "${renewer:-}" ] && [ "$attempt" -lt 3 ]; then
        echo "$main moved outside the landing queue — going round again, keeping the turn" >&2
        MIDAS_LAND_ATTEMPT=$((attempt + 1)) exec "$0" "${argv[@]}"
    fi
    unhold
    echo "$main was updated while this ran. Re-run: the rebase will pick it up." >&2
    exit 1
fi
echo "    $main is now ${sha:0:8}"

# The turn goes back now, not after the deploys: nothing a deploy does moves main.
land_outcome="landed"; land_sha="$sha"
if [ -n "${renewer:-}" ]; then
    kill "$renewer" 2>/dev/null
    midas land release --outcome landed --sha "$sha" >/dev/null 2>&1
    renewer=""
fi

[ -n "$held_here" ] && echo "    on $main, not live: deploys wait until a person deploys or \`midas deploy --release\`"
# Nothing the hub deploys after landings: on main is all it will be until a
# person or `--deploy` publishes it. Said, so the report does not promise "live".
if [ -z "$deploy" ] && ! midas project --get deploy 2>/dev/null | jq -e 'any(.[]; .after_landing == true)' >/dev/null 2>&1; then
    echo "note: the hub deploys nothing of $project after landings — it is on $main, not live. Say so, or deploy it (\`midas deploy\`)." >&2
fi
# On "Land it and finish": the hub ends and files the session once this is live.
if [ -n "$finish" ]; then
    midas sessions finish --sha "$sha" || echo "note: not finished — only a session the hub page runs is finished this way" >&2
fi
[ -n "$deploy" ] || { echo; echo "landed."; exit 0; }

# Asked for by name, after the landing, so a failed deploy never undoes one.
deploy_failed=""
for target in ${deploy//,/ }; do
    echo
    echo "==> midas deploy $target at ${sha:0:8}"
    midas deploy "$target" --sha "$sha" || deploy_failed="$deploy_failed $target"
done
if [ -n "$deploy_failed" ]; then
    echo "landed, but the deploy failed for:$deploy_failed — re-run: midas deploy <target> --sha $sha" >&2
    exit 1
fi
