#!/bin/sh
# script/update-policy: replace the files below with their current
# versions from the main branch of the prompts repo, and commit them. It
# does not push. Identical in all repos, and it updates itself.
set -eu

ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
RAW_URL="https://git.eeqj.de/sneak/prompts/raw/branch/main"

# Each entry is the path in prompts, a colon, then the path in this repo.
FILES="
prompts/REPO_POLICIES.md:docs/REPO_POLICIES.md
prompts/CODE_STYLEGUIDE.md:docs/CODE_STYLEGUIDE.md
script/update-policy:script/update-policy
"

die() {
    echo "update-policy: $*" >&2
    exit 1
}

main() {
    cd "$ROOT"
    [ ! -e prompts/REPO_POLICIES.md ] ||
        die "this is the prompts repo, where these files come from"
    [ ! -e REPO_POLICIES.md ] ||
        die "REPO_POLICIES.md is at the root;" \
            "move it into docs/ with git mv and fix the links to it first"

    paths=""
    for entry in $FILES; do
        paths="$paths ${entry#*:}"
    done
    [ -z "$(git status --porcelain -- $paths)" ] ||
        die "commit or discard your changes to these files first:$paths"

    # Every file is fetched before any is replaced. The temporary
    # directory is inside the repo so that mv renames: the running script
    # is replaced by a new file, never rewritten in place.
    tmp="$(mktemp -d "$ROOT/.update-policy.XXXXXX")"
    trap 'rm -rf "$tmp"' EXIT
    for entry in $FILES; do
        mkdir -p "$tmp/$(dirname "${entry#*:}")"
        wget -q -T 60 -O "$tmp/${entry#*:}" "$RAW_URL/${entry%%:*}" ||
            die "cannot fetch $RAW_URL/${entry%%:*}"
    done
    chmod 755 "$tmp/script/update-policy"

    for path in $paths; do
        mkdir -p "$(dirname "$path")"
        mv "$tmp/$path" "$path"
    done

    git add -- $paths
    if git diff --cached --quiet -- $paths; then
        echo "update-policy: already current, nothing to commit"
    else
        git commit -q -m "Update policy files from prompts" -- $paths
        echo "update-policy: committed; review it, then push"
    fi
}

main "$@"
