#!/bin/sh
# =============================================================
# upload_status.sh
# Uploads /tmp/<status-file>.json to remote nginx web server.
#
# Usage:  sh upload_status.sh [filename]
#   filename — optional, defaults to test-status.json
#
# 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.
# =============================================================
STATUS_FILE="${1:-test-status.json}"
LOCAL="/tmp/${STATUS_FILE}"
PASS_FILE="/home/node/scripts/.ftp_pass"
HOST="testing.tigerroad.net"
PORT="221"
REMOTE_USER="alupeta"
REMOTE_PATH="/html/${STATUS_FILE}"
# ── 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: ${STATUS_FILE} 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
