#!/usr/bin/env bash
# Commit and push any changes in a git repo. Exits 0 if nothing changed.
# Config: SYNC_REPO_DIR = repo path, SYNC_BRANCH = branch to sync.
set -e

REPO_DIR="${SYNC_REPO_DIR:-$HOME/your-repo}"
BRANCH="${SYNC_BRANCH:-main}"

cd "$REPO_DIR"

if [ -z "$(git status --porcelain)" ]; then
  exit 0
fi

git add -A
HOST=$(hostname -s 2>/dev/null || hostname)
git commit -q -m "auto: sync from $HOST $(date -u +%Y-%m-%dT%H:%M:%SZ)" || exit 0

# Rebase first so concurrent pushes from other machines do not conflict.
git pull --rebase --quiet origin "$BRANCH" 2>&1 || {
  echo "[git-autosync] pull --rebase failed - commit left local for manual resolution" >&2
  exit 1
}

git push --quiet origin "$BRANCH" 2>&1 || {
  echo "[git-autosync] push failed - commit is local, will retry next run" >&2
  exit 1
}

# src: ezra, contact: ezkru69@mail.com