diff --git a/services/.config/systemd/user/commit_notes.service b/services/.config/systemd/user/commit_notes.service new file mode 100644 index 0000000..7101a8f --- /dev/null +++ b/services/.config/systemd/user/commit_notes.service @@ -0,0 +1,12 @@ +[Unit] +Description=Automatically commit notes in directory +After=graphical.target + +[Service] +Type=simple +Environment=TIME_TO_COMMIT=120 UNCHANGED_RUNS_TO_PUSH=30 +ExecStart=/bin/bash -c '%h/.local/share/services/git-sync' +Restart=on-failure + +[Install] +WantedBy=multi-user.target diff --git a/services/.local/share/services/git-sync b/services/.local/share/services/git-sync new file mode 100755 index 0000000..8b1328a --- /dev/null +++ b/services/.local/share/services/git-sync @@ -0,0 +1,71 @@ +#!/usr/bin/env sh + +# time in seconds to check for changes to commit +TIME_TO_COMMIT=${GS_TIME_TO_COMMIT:-120} +# amount of times to check for changes *without changes occurring* to push to origin +UNCHANGED_RUNS_TO_PUSH=${GS_UNCHANGED_RUNS_TO_PUSH:-30} + +NOTEDIR=${WIKIROOT:-"$HOME/documents/notes"}/uni +[ -z "$NOTEDIR" ] && [ -z "$1" ] && { + msg "ERROR: Please supply a directory to sync." + exit 1 +} + +DIR="${NOTEDIR:-$1}" + +commit() { + run_git pull --ff-only --ff + + msg "Committing changes to $DIR" + run_git add . + # shellcheck disable=2039 + run_git commit --no-gpg-sign -m "Git sync: $(date +%F_%R) from ${HOSTNAME:-"$HOST"}" +} + +push() { + msg "No changes for $((UNCHANGED_RUNS_TO_PUSH * TIME_TO_COMMIT)) seconds, pushing to origin" + run_git push +} + +should_commit() { + if [ "$(run_git status --porcelain | wc -l)" -eq 0 ]; then + msg "No changes to commit in $DIR" + false + fi + msg "Found changes to commit in $DIR" + true +} + +should_push() { + if [ "$no_change_cycle" -ge "$UNCHANGED_RUNS_TO_PUSH" ]; then + true + else + false + fi +} + +run_git() { + git -C "$DIR" "$@" +} + +msg() { + echo "$1" +} + +no_change_cycle=0 +while true; do + if should_commit; then + commit + no_change_cycle=0 + fi + + if should_push; then + push + no_change_cycle=-9999 + fi + + msg "No changes for $((no_change_cycle * TIME_TO_COMMIT)) of $((UNCHANGED_RUNS_TO_PUSH * TIME_TO_COMMIT)) seconds, going back to sleep for $((TIME_TO_COMMIT)) seconds." + + no_change_cycle=$((no_change_cycle + 1)) + sleep "$TIME_TO_COMMIT" +done