#!/usr/bin/env bash
# Copyright (c) 2026 Shayne All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

set -euo pipefail

repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
cd "$repo_root"

if ! command -v mise >/dev/null 2>&1; then
  echo "mise is required to run depaware with the repo toolchain." >&2
  echo "Install and run: mise install" >&2
  exit 1
fi

targets=(
  ./cmd/derphole
  ./cmd/derptun
  ./cmd/derpssh
  ./cmd/derphole-probe
  ./cmd/derphole-web
)

depaware_files=(
  cmd/derphole/depaware.txt
  cmd/derptun/depaware.txt
  cmd/derpssh/depaware.txt
  cmd/derphole-probe/depaware.txt
  cmd/derphole-web/depaware.txt
)

if ! mise exec -- go run github.com/tailscale/depaware -update "${targets[@]}"; then
  echo "" >&2
  echo "depaware.txt generation failed." >&2
  exit 1
fi

perl -0pi -e 's/\n+\z/\n/' "${depaware_files[@]}"

if ! git diff --exit-code -- "${depaware_files[@]}" >/dev/null; then
  echo "" >&2
  echo "depaware.txt changed; please stage the updates and retry the commit." >&2
  exit 1
fi
