#!/bin/bash
# Upgrade n8n safely: backup -> tag rollback -> fix proxy env -> reboot container.
set -uo pipefail
TS=$(date +%Y%m%d-%H%M%S)
BK=/root/n8n-backup-$TS
VOL=/var/lib/docker/volumes/n8n_n8n_data/_data
say() { printf '\n### %s\n' "$*"; }

say "1/8 preconditions"
free_gb=$(df -BG / | awk 'NR==2{gsub("G","",$4); print $4}')
echo "  free disk: ${free_gb}G"
if [ "$free_gb" -lt 5 ]; then echo "ABORT: less than 5G free"; exit 1; fi
docker images --format '{{.Repository}}:{{.Tag}} {{.ID}}' | grep -q 'n8nio/n8n' || { echo "ABORT: n8n image missing"; exit 1; }
OLD_ID=$(docker inspect n8n --format '{{.Image}}')
echo "  current image id: ${OLD_ID:0:19}"

say "2/8 backup volume + compose"
mkdir -p "$BK"
cp -a /root/n8n/docker-compose.yml "$BK/docker-compose.yml"
tar czf "$BK/n8n_data.tar.gz" -C "$VOL" . 2>/dev/null
ls -lh "$BK" | tail -3

say "3/8 tag current image for rollback"
docker tag "$OLD_ID" "n8nio/n8n:rollback-$TS" && echo "  tagged n8nio/n8n:rollback-$TS"

say "4/8 stop n8n"
docker stop n8n >/dev/null && echo "  stopped"

say "5/8 fix proxy env in compose"
python3 - <<'PY'
p='/root/n8n/docker-compose.yml'
src=open(p).read()
new_proxy='http://172.19.0.1:20808'
before=src
src=src.replace('http://172.18.0.1:10809', new_proxy)
# make sure internal hosts bypass the proxy
if 'ollama' not in src.split('NO_PROXY:')[1].split('\n')[0]:
    old_line=[l for l in src.split('\n') if l.strip().startswith('NO_PROXY:')][0]
    new_line=old_line.rstrip() + ',ollama,172.19.0.1,qdrant,172.17.0.1'
    src=src.replace(old_line,new_line)
open(p,'w').write(src)
print("  proxy ->", new_proxy, "| changed:", src!=before)
PY
grep -E 'HTTP_PROXY|HTTPS_PROXY|NO_PROXY|N8N_PROXY:' /root/n8n/docker-compose.yml

say "6/8 switch the intent agent to the fast model"
python3 - <<'PY'
import json, sqlite3, shutil
db='/var/lib/docker/volumes/n8n_n8n_data/_data/database.sqlite'
shutil.copy2(db, db+'.pre-model-change')
c=sqlite3.connect(db)
rows=c.execute("select id,name,nodes from workflow_entity").fetchall()
changed=[]
for wid,name,nodes_json in rows:
    nodes=json.loads(nodes_json)
    touched=False
    for n in nodes:
        if n.get('type','').endswith('lmChatOpenAi') and n.get('name')=='Intent Chat Model':
            p=n.setdefault('parameters',{})
            cur=p.get('model')
            if isinstance(cur,dict):
                cur['value']='gemini/gemini-3.5-flash-lite'
                cur['cachedResultName']='gemini/gemini-3.5-flash-lite'
            else:
                p['model']='gemini/gemini-3.5-flash-lite'
            touched=True
    if touched:
        c.execute("update workflow_entity set nodes=? where id=?", (json.dumps(nodes,ensure_ascii=False), wid))
        changed.append(name)
c.commit()
print("  workflows updated:", changed or "none")
PY

say "7/8 pull latest and start"
cd /root/n8n || exit 1
if ! docker compose pull n8n; then
  echo "  PULL FAILED -> restarting with the existing image"
  docker compose up -d n8n
  echo "  n8n restarted on the previous image ($(docker exec n8n n8n --version 2>/dev/null | tail -1))"
  exit 1
fi
docker compose up -d n8n 2>&1 | tail -4

say "8/8 verify"
for i in $(seq 1 30); do
  ver=$(docker exec n8n n8n --version 2>/dev/null | tail -1)
  [ -n "$ver" ] && break
  sleep 3
done
echo "  version now: ${ver:-unknown}"
docker ps --filter name=n8n --format '  {{.Names}} | {{.Image}} | {{.Status}}'
docker exec n8n sh -c 'wget -q -T 4 -O /dev/null http://127.0.0.1:5678/healthz && echo "  healthz OK" || echo "  healthz FAIL"' 2>&1 | tail -1
echo "  workflows: $(python3 -c "import sqlite3;print(sqlite3.connect('/var/lib/docker/volumes/n8n_n8n_data/_data/database.sqlite').execute('select count(*) from workflow_entity').fetchone()[0])" 2>/dev/null)"
printf '  backup: %s\n' "$BK"
printf '  rollback image: n8nio/n8n:rollback-%s\n' "$TS"
