#!/bin/sh
# script/update-policy: replace the files below, and the style guides
# for the repo's languages, 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
"

# The style guide for each language the repo uses, and the HTTP server
# conventions for Go code using net/http. Go and Python are found by
# their file at the root, JavaScript by tracked .js or .ts files: many
# Go repos have a package.json only to pin prettier.
language_files() {
    if [ -e go.mod ]; then
        echo prompts/CODE_STYLEGUIDE_GO.md:docs/CODE_STYLEGUIDE_GO.md
        if git grep -q '"net/http"' -- '*.go'; then
            echo prompts/GO_HTTP_SERVER_CONVENTIONS.md:docs/GO_HTTP_SERVER_CONVENTIONS.md
        fi
    fi
    if [ -n "$(git ls-files -- '*.js' '*.ts')" ]; then
        echo prompts/CODE_STYLEGUIDE_JS.md:docs/CODE_STYLEGUIDE_JS.md
    fi
    if [ -e pyproject.toml ] || [ -e setup.py ]; then
        echo prompts/CODE_STYLEGUIDE_PYTHON.md:docs/CODE_STYLEGUIDE_PYTHON.md
    fi
}

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"

    FILES="$FILES $(language_files)"
    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 "$@"
