#!/bin/sh
# =============================================================
# upload_status.sh
# Uploads /tmp/test-status.json to remote nginx web server.
#
# Called from n8n Execute Command nodes after every status
# change (lock acquire/release, test start, test complete).
#
# SETUP (inside n8n Docker container — run once):
#   apk add sshpass openssh-client
#   echo 'YOUR_SFTP_PASSWORD' > /home/node/scripts/.ftp_pass
#   chmod 600 /home/node/scripts/.ftp_pass
#   chmod +x /home/node/scripts/upload_status.sh
#
# ALWAYS exits 0 — upload failures must never break n8n flow.
# =============================================================

LOCAL="/tmp/test-status.json"
PASS_FILE="/home/node/scripts/.ftp_pass"
HOST="testing.tigerroad.net"
PORT="221"
REMOTE_USER="alupeta"
REMOTE_PATH="/html/test-status.json"

# ── Soft-fail guards ──────────────────────────────────────────
if [ ! -f "$LOCAL" ]; then
  echo "SKIP: local file not found at $LOCAL"
  exit 0
fi

if [ ! -f "$PASS_FILE" ]; then
  echo "SKIP: password file not found at $PASS_FILE"
  exit 0
fi

if ! command -v sshpass > /dev/null 2>&1; then
  echo "SKIP: sshpass not installed (run: apk add sshpass openssh-client)"
  exit 0
fi

# ── Upload ────────────────────────────────────────────────────
sshpass -f "$PASS_FILE" sftp \
  -o StrictHostKeyChecking=no \
  -o BatchMode=no \
  -o ServerAliveInterval=50 \
  -o ServerAliveCountMax=15 \
  -P "$PORT" \
  "${REMOTE_USER}@${HOST}" << SFTP_CMDS
put $LOCAL $REMOTE_PATH
bye
SFTP_CMDS

UPLOAD_STATUS=$?

if [ "$UPLOAD_STATUS" -eq 0 ]; then
  echo "OK: test-status.json uploaded → ${HOST}:${REMOTE_PATH}"
else
  echo "WARN: sftp exited with status $UPLOAD_STATUS (non-fatal, workflow continues)"
fi

# Always exit 0 — n8n treats non-zero as hard failure
exit 0
