#!/usr/bin/env bash
set -euo pipefail

base_commit=ee0da84ab9e04ac7610e28580af62c365e898389
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
repo=${1:-.}
patches=("$script_dir"/0*.patch)

git -C "$repo" rev-parse --git-dir >/dev/null
if [[ -n $(git -C "$repo" status --porcelain) ]]; then
    echo "Refusing to apply to a dirty worktree." >&2
    exit 1
fi
if ((${#patches[@]} == 0)) || [[ ! -f ${patches[0]} ]]; then
    echo "No numbered patch files found in $script_dir" >&2
    exit 1
fi

head_commit=$(git -C "$repo" rev-parse HEAD)
mapfile -t recent_commits < <(
    git -C "$repo" rev-list --max-count="${#patches[@]}" --reverse HEAD
)
patches_match=true
((${#recent_commits[@]} == ${#patches[@]})) || patches_match=false
for i in "${!patches[@]}"; do
    $patches_match || break
    patch_id=$(git patch-id --stable <"${patches[$i]}" | awk '{print $1}')
    commit_id=$(
        git -C "$repo" show --pretty=format: "${recent_commits[$i]}" |
            git patch-id --stable | awk '{print $1}'
    )
    [[ $patch_id == "$commit_id" ]] || patches_match=false
done
first_parent=""
if ((${#recent_commits[@]} > 0)); then
    first_parent=$(
        git -C "$repo" rev-parse --verify "${recent_commits[0]}^" 2>/dev/null || true
    )
fi
if $patches_match && [[ $first_parent == "$base_commit" ]]; then
    echo "OpProf patch series is already applied."
    exit 0
fi

if [[ $head_commit == "$base_commit" ]]; then
    git -C "$repo" am "${patches[@]}"
    echo "Applied OpProf patch series to $repo"
    exit 0
fi
if $patches_match; then
    echo "Refusing to treat OpProf patches as already applied:" >&2
    echo "first patch parent is $first_parent, expected $base_commit" >&2
    exit 1
fi

echo "Refusing to apply: HEAD is $head_commit; expected $base_commit" >&2
echo "or the exact OpProf patch series rooted at that base." >&2
exit 1
