#!/usr/bin/env bash
set -u
cd "$(dirname "$0")/.."
POLL_SECONDS="${POLL_SECONDS:-60}"

log() {
  printf "[%s] %s\n" "$(date '+%F %T')" "$*"
}

pull_once() {
  git remote get-url origin >/dev/null 2>&1 || return 0
  local branch
  branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
  [ -n "$branch" ] || return 0
  git pull --rebase origin "$branch" || true
}

push_once() {
  git remote get-url origin >/dev/null 2>&1 || return 0
  git push || true
}
while true; do
  fswatch -1 -r --exclude '\\.git' --exclude 'node_modules' --exclude '.next' --exclude 'android/app/build' . &
  fswatch_pid=$!
  start_ts="$(date +%s)"
  timed_out=0

  while kill -0 "$fswatch_pid" >/dev/null 2>&1; do
    now_ts="$(date +%s)"
    if [ $((now_ts - start_ts)) -ge "$POLL_SECONDS" ]; then
      timed_out=1
      kill "$fswatch_pid" >/dev/null 2>&1 || true
      wait "$fswatch_pid" >/dev/null 2>&1 || true
      break
    fi
    sleep 1
  done

  if [ "$timed_out" -eq 1 ]; then
    log "no local change, polling remote"
    pull_once
    continue
  fi

  wait "$fswatch_pid" >/dev/null 2>&1 || true
  log "change detected, committing"
  git add . || true
  git commit -m "chore: auto-sync" || true
  pull_once
  push_once
done
