#!/usr/bin/env bash
# PR #24612 (fix(clients): default GitLab clones to HTTPS), for #13350.
# Claim: already-fixed. The branch's HTTPS default was reverted on the branch (19d07ef27a), so its head has
# no net diff, and the bug in #13350 (a GitLab clone failing when the host refuses SSH) is handled on main
# by #23170 (a49d18cf3b): an SSH clone refused by key or host key is retried over HTTPS.
# Shows: the PR's net diff is empty, and a GitLab clone case passes on main and fails with #23170's
# retry disabled. Needs deps installed (`vp i`). Run from the root of a clean t3code checkout.
set -euo pipefail

ok=1
pass() { echo "PASS  $*"; }
fail() { echo "FAIL  $*"; ok=0; }

if [ -n "$(git status --porcelain)" ]; then
  echo "refusing to run on a dirty tree"
  exit 2
fi
ORIG=$(git symbolic-ref -q --short HEAD || git rev-parse HEAD)
WORK=$(mktemp -d)
TEST=apps/server/src/sourceControl/SourceControlRepositoryService.test.ts
SERVICE=apps/server/src/sourceControl/SourceControlRepositoryService.ts
cleanup() {
  git checkout -q -f -- . 2>/dev/null || true
  git checkout -q -f "$ORIG"
  rm -rf "$WORK"
}
trap 'rc=$?; cleanup; [ "${PROOF_DONE:-0}" = 1 ] && exit 0; [ "$rc" -ne 0 ] && exit "$rc"; exit 1' EXIT

git fetch -q origin main
MAIN=$(git rev-parse FETCH_HEAD)
git fetch -q origin pull/24612/head
PR_HEAD=$(git rev-parse FETCH_HEAD)
MB=$(git merge-base "$MAIN" "$PR_HEAD")
FIX=a49d18cf3b97fa48681d0ed1f9c6caedbd292f54
echo "main=$MAIN pr_head=$PR_HEAD merge_base=$MB fix=$FIX"

# 1. The PR head changes nothing: its HTTPS default was reverted on the branch.
if git diff --quiet "$MB" "$PR_HEAD"; then
  pass "the PR head has no net diff against its merge-base"
else
  fail "the PR head still changes: $(git diff --stat "$MB" "$PR_HEAD" | tail -1)"
fi
merged_tree=$(git merge-tree --write-tree "$MAIN" "$PR_HEAD")
if [ "$merged_tree" = "$(git rev-parse "$MAIN^{tree}")" ]; then
  pass "merging the PR head into main yields main's tree unchanged"
else
  fail "merging the PR head into main changes main's tree"
fi
last=$(git log -1 --format=%s "$PR_HEAD")
if [ "$last" = "revert(gitlab): keep SSH as the GitLab clone default" ] \
  && git show "$PR_HEAD:packages/source-control-gitlab/src/shared/definition.ts" | grep -qF 'defaultCloneTransport: "ssh",'; then
  pass "the branch's last commit is '$last'; GitLab's clone default on the PR head is SSH, as on main"
else
  fail "the PR head's last commit is '$last' or its GitLab default is not SSH"
fi

# 2. #23170 added the HTTPS retry for refused SSH clones, and it is on main.
if git merge-base --is-ancestor "$FIX" "$MAIN" \
  && [ "$(git log -1 --format=%s "$FIX")" = "fix(source-control): clones retry over HTTPS when the SSH key is refused (#23170)" ] \
  && git show "$FIX:$SERVICE" | grep -qF 'function httpsFallbackUrl(' \
  && ! git show "$FIX^:$SERVICE" | grep -qF 'function httpsFallbackUrl('; then
  pass "#23170 ($(git rev-parse --short "$FIX")) is on main and added httpsFallbackUrl, the HTTPS retry for refused SSH clones"
else
  fail "#23170 is not on main or did not add the HTTPS retry"
fi

# 3. Behavioral on main: issue #13350's clone (GitLab SSH URL, no protocol, as the picker sends it),
#    refused by host key or by key, is retried over HTTPS and the project's remote is HTTPS.
write_case() {
  cat >> "$TEST" <<'EOF'

// prove-pr-24612: issue #13350's GitLab clone, where the host refuses SSH, is retried over HTTPS.
it.effect.each([
  ["the SSH host key is not trusted", "host_key_unverified"],
  ["the SSH key is refused", "authentication_failed"],
] as const)("prove-pr-24612 retries a GitLab SSH clone over HTTPS when %s", ([, reason]) =>
  Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    const parent = yield* fs
      .makeTempDirectoryScoped({ prefix: "t3-prove-24612-" })
      .pipe(Effect.orDie);
    const urls: Array<string> = [];
    const git = {
      execute: (input: GitVcsDriver.ExecuteGitInput) =>
        Effect.gen(function* () {
          const url = input.args.at(-2)!;
          urls.push(url);
          if (url.startsWith("https://")) return processOutput();
          return yield* new GitCommandError({
            operation: input.operation,
            command: "git",
            cwd: input.cwd,
            reason,
            detail: "Git command exited with a non-zero status.",
          });
        }),
    } satisfies Partial<GitVcsDriver.GitVcsDriver["Service"]>;
    const result = yield* Effect.gen(function* () {
      const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
      return yield* service.cloneRepository({
        remoteUrl: "git@gitlab.com:group/subgroup/project.git",
        destinationPath: path.join(parent, "project"),
      });
    }).pipe(Effect.provide(layer({ git }).pipe(Layer.orDie)));

    assert.deepStrictEqual(urls, [
      "git@gitlab.com:group/subgroup/project.git",
      "https://gitlab.com/group/subgroup/project.git",
    ]);
    assert.strictEqual(result.remoteUrl, "https://gitlab.com/group/subgroup/project.git");
  }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
EOF
}
run_case() {
  (cd apps/server && vp test run --reporter=verbose src/sourceControl/SourceControlRepositoryService.test.ts -t "prove-pr-24612") > "$1" 2>&1 || true
  grep -E "prove-pr-24612|Tests +[0-9]" "$1" | sed -E 's/ +[0-9]+ms$//' || tail -20 "$1"
}

git checkout -q --detach "$MAIN"
write_case
run_case "$WORK/main.log"
if grep -qE "Tests +2 passed" "$WORK/main.log" && ! grep -qE "Tests +.*failed" "$WORK/main.log"; then
  pass "on main, a GitLab SSH clone refused by host key or by key is retried at https://gitlab.com/group/subgroup/project.git and the remote is HTTPS"
else
  fail "the GitLab clone retry case did not pass on main"
fi

# 4. Same case on main with #23170's retry disabled: it fails, so the pass comes from #23170.
perl -0pi -e 's/(function httpsFallbackUrl\(\n  input: SourceControlCloneRepositoryInput,\n  prepared: SourceControlPreparedClone,\n\): string \| null \{\n)/${1}  return null;\n/' "$SERVICE"
if git diff --quiet -- "$SERVICE"; then
  fail "could not disable httpsFallbackUrl on main (its signature changed)"
else
  run_case "$WORK/mutant.log"
  if grep -qE "Tests +2 failed" "$WORK/mutant.log"; then
    pass "with httpsFallbackUrl disabled, both cases fail: without #23170 the refused SSH clone is not retried"
  else
    fail "the case did not fail with #23170's retry disabled"
  fi
fi
git checkout -q -f -- .

if [ "$ok" = 1 ]; then
  echo "VERDICT: CLOSE (already-fixed) - the PR head has no net diff, and #23170 already retries a refused GitLab SSH clone over HTTPS"
  PROOF_DONE=1; exit 0
fi
echo "VERDICT: KEEP - at least one check failed"
exit 1
