#!/bin/bash
# Auto-sync case repos to Gitea
# Runs via crontab every minute, commits and pushes any changes found.

CASES_DIR="/home/chaim/legal-ai/data/cases"
LOG="/home/chaim/legal-ai/data/.auto-sync.log"

export GIT_AUTHOR_NAME="Ezer Mishpati"
export GIT_AUTHOR_EMAIL="legal@local"
export GIT_COMMITTER_NAME="Ezer Mishpati"
export GIT_COMMITTER_EMAIL="legal@local"
export GIT_TERMINAL_PROMPT=0

for case_dir in "$CASES_DIR"/*/; do
    [ -d "$case_dir/.git" ] || continue

    case_name=$(basename "$case_dir")

    # Ensure safe.directory is set for this repo
    git config --global --get-all safe.directory | grep -qF "$case_dir" \
        || git config --global --add safe.directory "$case_dir"

    cd "$case_dir" || continue

    # Check for any changes (modified, new, deleted)
    changes=$(git status --porcelain 2>/dev/null)
    [ -z "$changes" ] && continue

    # Stage all changes
    git add -A 2>/dev/null

    # Count changed files
    count=$(git diff --cached --name-only 2>/dev/null | wc -l)
    [ "$count" -eq 0 ] && continue

    msg="סנכרון אוטומטי — ${count} קבצים שונו"

    # Commit
    if git commit -m "$msg" --quiet 2>/dev/null; then
        # Push only if remote exists
        if git remote get-url origin >/dev/null 2>&1; then
            if git push origin HEAD --quiet 2>/dev/null; then
                echo "$(date '+%Y-%m-%d %H:%M:%S') | $case_name | $count files synced + pushed" >> "$LOG"
            else
                echo "$(date '+%Y-%m-%d %H:%M:%S') | $case_name | $count files committed, push FAILED" >> "$LOG"
            fi
        else
            echo "$(date '+%Y-%m-%d %H:%M:%S') | $case_name | $count files committed (no remote)" >> "$LOG"
        fi
    else
        echo "$(date '+%Y-%m-%d %H:%M:%S') | $case_name | commit FAILED" >> "$LOG"
    fi
done
