#!/usr/bin/env bash
# Refresh the ephemeral llvm-mos checkout to the latest upstream main,
# then re-apply our backend (symlinks + patches).
#
# This is the ONLY script that is allowed to destructively reset the
# clone.  installLlvmMos.sh intentionally refuses to do so because a
# reset would destroy any applied patches.

set -euo pipefail
source "$(dirname "$0")/common.sh"

LLVM_SRC="$TOOLS_DIR/llvm-mos"

[ -d "$LLVM_SRC/.git" ] || die "llvm-mos checkout not found; run setup.sh first"

currentBranch="$(git -C "$LLVM_SRC" rev-parse --abbrev-ref HEAD)"
if [ "$currentBranch" != "main" ]; then
    die "llvm-mos is on branch '$currentBranch', expected main. Refusing to reset."
fi

# First un-apply our patches so the reset only discards upstream drift,
# not our work.  Symlinks are unaffected by git reset since untracked
# directories are left alone (our symlinks live inside tracked dirs but
# are untracked files themselves).
log "reverting any applied patches"
for patch in "$PROJECT_ROOT"/patches/*.patch; do
    [ -f "$patch" ] || continue
    if git -C "$LLVM_SRC" apply --reverse --check "$patch" >/dev/null 2>&1; then
        git -C "$LLVM_SRC" apply --reverse "$patch"
        log "  reverted: $(basename "$patch")"
    fi
done

# Symlinks from applyBackend.sh are untracked files inside tracked
# directories.  git reset --hard leaves them in place, but we clean
# them proactively so the fast-forward sees a truly clean tree.
log "removing symlinks under $LLVM_SRC pointing into $PROJECT_ROOT/src"
find "$LLVM_SRC" -type l | while read -r link; do
    target="$(readlink -f "$link" || true)"
    case "$target" in
        "$PROJECT_ROOT"/src/*) rm "$link" ;;
    esac
done

if ! git -C "$LLVM_SRC" diff --quiet || ! git -C "$LLVM_SRC" diff --cached --quiet; then
    die "llvm-mos checkout still has local changes after cleanup. Inspect with: git -C $LLVM_SRC status"
fi

log "fetching and resetting to origin/main"
git -C "$LLVM_SRC" fetch --depth=1 origin main
git -C "$LLVM_SRC" reset --hard FETCH_HEAD

log "re-applying backend"
"$PROJECT_ROOT/scripts/applyBackend.sh"

log "update complete"
