#!/usr/bin/env bash
# Back up everything to Gitea:
#   1. Commit any new/changed loose files in the root repo, then push it.
#   2. Push each subproject repo's current branch to its `gitea` remote.
#
# GitHub remotes (origin) are left untouched — push those yourself as usual.
# Safe to run repeatedly: skips the root commit when there's nothing to commit,
# and skips any subrepo that has no `gitea` remote.

set -u
cd "$(dirname "$0")" || exit 1

# First connect to the LAN Gitea host shouldn't block on host-key prompts.
export GIT_SSH_COMMAND="ssh -o StrictHostKeyChecking=accept-new"

green() { printf '\033[32m%s\033[0m\n' "$1"; }
red()   { printf '\033[31m%s\033[0m\n' "$1"; }

echo "=== root repo ==="
if [ -n "$(git status --porcelain)" ]; then
  git add -A
  git commit -q -m "Backup $(date '+%Y-%m-%d %H:%M')"
  echo "committed changes"
else
  echo "no changes to commit"
fi
if git push gitea HEAD >/dev/null 2>&1; then green "  pushed root -> gitea"; else red "  push FAILED (root)"; fi

echo
echo "=== subproject repos ==="
for d in */; do
  d="${d%/}"
  [ -d "$d/.git" ] || continue
  if ! git -C "$d" remote get-url gitea >/dev/null 2>&1; then
    echo "  $d: no gitea remote, skipping"
    continue
  fi
  branch="$(git -C "$d" symbolic-ref --short HEAD 2>/dev/null || echo HEAD)"
  if git -C "$d" push gitea "$branch" >/dev/null 2>&1; then
    green "  $d: pushed $branch -> gitea"
  else
    red "  $d: push FAILED ($branch)"
  fi
done

echo
green "done."
