#!/usr/bin/bash
# git-repo-sync <name> <dest> <mode> [after_pull]
# Run at login by git-repo-sync@<name>.service (installed by danmwallace.linux.git_repo_sync).
#
#   pull  skip if the clone has uncommitted changes, else pull --ff-only, then run after_pull
#   sync  commit everything, pull --rebase, push, then run after_pull
#
# It never forces anything and never leaves a half-finished rebase:
#   - origin unreachable (offline, or a key GitHub doesn't know): a line on stderr, exit 0
#   - a rebase, merge, cherry-pick or revert in progress, or unmerged files (you are
#     working in the clone): exit 0
#   - usually nothing new is on origin: the sync commits and pushes, no rebase at all
#   - a sync whose commit fails or whose rebase conflicts: the rebase is aborted and the
#     sync's own commit undone (your changes are back as uncommitted edits), a desktop
#     notification says so, exit 0; the next login tries again
#   - a push that fails after a clean rebase: the rebased commit stays for the next
#     login to push, with a notification
# A clone with no git identity commits as <user>@<host>.
# Exit 2 on bad usage, 1 only when the clone itself is unusable.
set -uo pipefail

usage() { echo "usage: git-repo-sync <name> <dest> pull|sync [after_pull]" >&2; exit 2; }
(($# == 3 || $# == 4)) || usage
name=$1 dest=$2 mode=$3 after_pull=${4:-}
[[ "$mode" == pull || "$mode" == sync ]] || usage

say() { echo "git-repo-sync ${name}: $*" >&2; }
notify() { command -v notify-send >/dev/null 2>&1 && notify-send -a git-repo-sync -u critical "${name} sync needs you" "$1"; say "$1"; }

git_dir=$(git -C "$dest" rev-parse --absolute-git-dir 2>/dev/null) || { notify "${dest} is not a git clone any more"; exit 1; }
cd "$dest" || exit 1

exec 9>"${git_dir}/git-repo-sync.lock"
flock -n 9 || { say "another sync is running"; exit 0; }

for marker in rebase-merge rebase-apply MERGE_HEAD CHERRY_PICK_HEAD REVERT_HEAD sequencer; do
    if [[ -e "${git_dir}/${marker}" ]]; then
        say "a rebase, merge, cherry-pick or revert is in progress; leaving it to you"
        exit 0
    fi
done
if [[ -n "$(git ls-files -u)" ]]; then
    say "unmerged files (a conflict is waiting to be resolved); leaving it to you"
    exit 0
fi

if ! timeout 15 git ls-remote --exit-code origin HEAD >/dev/null 2>&1; then
    say "origin unreachable; skipping"
    exit 0
fi

run_after_pull() {
    [[ -n "$after_pull" ]] || return 0
    bash -c "$after_pull" || say "after_pull failed (exit $?)"
}

dirty() { [[ -n "$(git status --porcelain)" ]]; }

if [[ "$mode" == pull ]]; then
    if dirty; then
        say "uncommitted changes; not pulling"
        exit 0
    fi
    if ! out=$(git pull --ff-only --quiet 2>&1); then
        notify "pull --ff-only failed: $(head -1 <<<"$out")"
        exit 0
    fi
    run_after_pull
    exit 0
fi

# sync
before=$(git rev-parse HEAD)
committed=0
if dirty; then
    host=$(uname -n); host=${host%%.*}
    identity=()
    [[ -n "$(git config user.email)" ]] || identity=(-c "user.name=$(id -un)" -c "user.email=$(id -un)@${host}")
    git add -A
    if ! out=$(git "${identity[@]}" commit --quiet -m "${name} sync from ${host} ($(date '+%Y-%m-%d %H:%M'))" 2>&1); then
        git reset --quiet   # unstage again: the clone stays as it was
        notify "commit failed: $(head -1 <<<"$out")"
        exit 0
    fi
    committed=1
fi

undo() {  # put the clone back as it was before this run
    git rebase --abort >/dev/null 2>&1
    if ((committed)); then
        git reset --quiet --mixed "$before"
    fi
}

# Fetch first. Usually nothing new arrived (only this machine commits), and the sync just
# pushes: no rebase, so files Syncthing or an editor write meanwhile are left alone.
if ! out=$(git fetch --quiet origin 2>&1); then
    undo
    say "fetch failed: $(head -1 <<<"$out"); skipping"
    exit 0
fi
if ! upstream=$(git rev-parse --verify --quiet '@{upstream}'); then
    undo
    notify "the branch has no upstream to sync with"
    exit 0
fi
if [[ -n "$(git rev-list HEAD.."$upstream")" ]]; then
    # Something new on GitHub (e.g. a Hermes note): rebase onto it, carrying any edit
    # that lands meanwhile across in an autostash instead of refusing to start.
    if ! out=$(git rebase --quiet --autostash "$upstream" 2>&1); then
        undo
        notify "$(grep -m1 CONFLICT <<<"$out" || head -1 <<<"$out")"
        exit 0
    fi
fi
if [[ "$(git rev-parse HEAD)" != "$upstream" ]]; then
    if ! out=$(git push --quiet 2>&1); then
        notify "push failed: $(head -1 <<<"$out")"
        exit 0
    fi
fi
run_after_pull
exit 0
