#!/usr/bin/env sh
# Export every n8n workflow to one JSON file each and commit the change to Git (lesson AUT-204-L04).
# Run it daily (cron) and after every important edit. Exports workflows only: credentials stay in n8n, encrypted.
#
#   REPO=/srv/n8n-workflows ./export_workflows.sh "why this change"
#
# With Docker Compose, run the n8n CLI inside the container instead (see the lesson):
#   N8N="docker compose exec -T -u node n8n n8n" ...  and export to a mounted folder.
set -eu
REPO="${REPO:-./n8n-workflows}"
N8N="${N8N:-n8n}"
MSG="${1:-scheduled export}"

mkdir -p "$REPO/workflows"
cd "$REPO"
[ -d .git ] || git init -q

# --backup = --all --pretty --separate: one readable file per workflow, named by workflow id
rm -f workflows/*.json
$N8N export:workflow --backup --output=workflows/ >/dev/null

# Refuse to commit anything that looks like a secret (credentials are not exported, but a token pasted
# into a node parameter would be).
if grep -RIlE '(Bearer [A-Za-z0-9._-]{20,}|sk-[A-Za-z0-9]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY)' workflows/ ; then
  echo "possible secret in exported workflow; fix the workflow (use a credential) and export again" >&2
  exit 3
fi

git add -A workflows
if git diff --cached --quiet; then
  echo "no workflow changes"
else
  git -c user.name="n8n export" -c user.email="n8n-export@localhost" commit -q -m "$MSG"
  git log -1 --stat --format='%h %s'
fi
