#!/bin/sh
set -eu

einfo() { printf '* %s\n' "$*"; }

pwd=$(pwd)

remote_name=openbsd-src
remote_url=https://github.com/openbsd/src
wt=/tmp/acme-client-portable-update-wt
last_synced=$pwd/_tools/last-synced
pd=$pwd/patches

cleanup() {
	[ -d "$wt" ] || return

	cd "$pwd"
	git worktree remove "$wt"

	rm -rf "$pd"
}
trap cleanup EXIT

einfo 'Ensuring remote...'
if ! git remote -v | grep -qF "$remote_url"; then
	git remote add "$remote_name" "$remote_url"
fi

einfo 'Fetching ...'
git fetch "$remote_name" --prune

if [ -d "$wt" ]; then
	einfo >&2 'Worktree seems to already exist? Please clean up.'
	exit 1
fi

einfo "Generating patched since $(cat "$last_synced")..."
rm -rf "$pd"
mkdir -p "$pd"
git format-patch -o "$pd" \
	"$(cat "$last_synced")..$remote_name/master" -- usr.sbin/acme-client

einfo 'Creating worktree...'
git worktree add "$wt" openbsd
cd "$wt"

einfo 'Applying patches...'
for patch in $(find "$pd" -type f | sort); do
	git am "$patch"
	GIT_EDITOR='fold -sw 72 "$1" > "$1.new" && mv "$1.new" "$1" && :' \
		git commit --amend
done

einfo 'Recording last synced commit...'
git rev-parse openbsd-src/master >"$last_synced"

einfo 'Done.'
