git_ssh_setup() {
  mkdir -p /root/.ssh
  cp /workspace/git-ssh/ssh-privatekey /root/.ssh/id_rsa
  chmod 600 /root/.ssh/id_rsa
  timeout 10 ssh-keyscan github.com >> /root/.ssh/known_hosts 2>/dev/null || true
  timeout 10 ssh-keyscan -p 443 ssh.github.com >> /root/.ssh/known_hosts 2>/dev/null || true
  write_github_proxy_command
  export GIT_SSH_COMMAND="ssh -i /root/.ssh/id_rsa -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o ServerAliveInterval=10 -o ServerAliveCountMax=2 -o ProxyCommand='node /tmp/hwlab-github-proxy-connect.mjs 127.0.0.1 10808 %h %p'"
  git config --global url."ssh://git@ssh.github.com:443/".insteadOf "git@github.com:"
  git config --global url."ssh://git@ssh.github.com:443/".insteadOf "ssh://git@github.com/"
}

write_github_proxy_command() {
  cat > /tmp/hwlab-github-proxy-connect.mjs <<'NODE_PROXY'
// __HWLAB_GITHUB_PROXY_CONNECT_MJS__
NODE_PROXY
  chmod 0700 /tmp/hwlab-github-proxy-connect.mjs
}

git_now_ms() {
  node -e 'console.log(Date.now())' 2>/dev/null || date +%s000
}

git_timed() {
  phase="$1"
  timeout_seconds="$2"
  shift 2
  started_ms="$(git_now_ms)"
  echo '{"event":"git-operation","phase":"'"$phase"'","status":"started","timeoutSeconds":'"$timeout_seconds"'}' >&2
  set +e
  timeout "$timeout_seconds" "$@"
  status="$?"
  set -e
  finished_ms="$(git_now_ms)"
  duration_ms="$((finished_ms - started_ms))"
  if [ "$status" -eq 0 ]; then
    echo '{"event":"git-operation","phase":"'"$phase"'","status":"succeeded","durationMs":'"$duration_ms"'}' >&2
    return 0
  fi
  if [ "$status" -eq 124 ] || [ "$status" -eq 137 ]; then
    echo '{"event":"git-operation","phase":"'"$phase"'","status":"failed","reason":"timeout","durationMs":'"$duration_ms"',"timeoutSeconds":'"$timeout_seconds"'}' >&2
  else
    echo '{"event":"git-operation","phase":"'"$phase"'","status":"failed","exitCode":'"$status"',"durationMs":'"$duration_ms"'}' >&2
  fi
  return "$status"
}
