/ patcher
#!/bin/tcsh -f
#
# patcher -- stage, review, and conditionally apply the most recent
# downloaded patch for the Yioop repo.
#
# Steps automated:
#   1. cd to the repo root
#   2. remove any stale *.patch files already in the repo root
#   3. move freshly downloaded *.patch files in from ~/Downloads
#   4. less the most recent patch for review
#   5. prompt y/n -- on y run git apply, otherwise exit untouched

# tcsh aborts with "set: No match." when a glob in a `set (...)` list
# matches nothing. nonomatch tells it to leave an unmatched glob as
# the literal pattern instead, which the != checks below rely on.
set nonomatch

# --- 1. get to the repo root -------------------------------------------
cd /opt/homebrew/var/www/git/yioop
if ($status != 0) then
    echo "patcher: could not cd into the repo; aborting."
    exit 1
endif

# --- 2. drop stale patches already sitting in the repo root ------------
set stale = ( *.patch )
if ("$stale" != "*.patch") then
    echo "patcher: removing stale patch file(s): $stale"
    rm -f *.patch
endif

# --- 3. bring in freshly downloaded patches ----------------------------
set downloaded = ( ~/Downloads/*.patch )
if ("$downloaded" == "$HOME/Downloads/*.patch") then
    echo "patcher: no *.patch files found in ~/Downloads; aborting."
    exit 1
endif
mv ~/Downloads/*.patch .
if ($status != 0) then
    echo "patcher: could not move patches in from ~/Downloads; aborting."
    exit 1
endif

# --- 4. pick the most recent patch and show it -------------------------
# ls -t sorts newest first; take the first entry.
set patch = `ls -t *.patch | head -1`
if ("$patch" == "") then
    echo "patcher: no patch file present after move; aborting."
    exit 1
endif
echo "patcher: reviewing $patch"
less $patch

# --- 5. prompt, then apply or exit -------------------------------------
echo -n "Apply $patch with git apply? (y/n) "
set answer = $<
if ("$answer" == "y" || "$answer" == "Y") then
    git apply --check $patch
    if ($status != 0) then
        echo "patcher: git apply --check failed; not applying $patch."
        exit 1
    endif
    git apply $patch
    if ($status == 0) then
        echo "patcher: $patch applied cleanly."
        set commit=`echo $patch | sed 's/-/ /g; s/\.patch$//'`
        echo "If you like this patch here are the files it modifies/adds"
        git status
        echo "If you want to commit this, you can copy and paste:"
        echo "git commit -a -m '$commit'"
    else
        echo "patcher: git apply reported errors for $patch."
        exit 1
    endif
else
    echo "patcher: left $patch in place, nothing applied."
    exit 0
endif
X