#!/bin/bash
set -euo pipefail

# -------------------------------
# Uptime Kuma Push Keys
# -------------------------------
KUMA_KEY_RCLONE="52tJPNfjOu"
KUMA_KEY_SPS="KXb9eO9yhs"
KUMA_KEY_LUCA="1rSmlQsvIC"

# -------------------------------
# Initial States
# -------------------------------
BCK_SPS="nok"
BCK_PBS_SPS="nok"
BCK_PBS_LUCA="nok"

notify_kuma() {
  local kuma_key="$1"
  local status="$2"
  local msg="$3"

  # Basic URL encoding (replace spaces and some common special chars)
  local encoded_msg
  encoded_msg=$(echo "$msg" | sed -e 's/ /+/g' -e 's/:/%3A/g' -e 's/\[/%5B/g' -e 's/\]/%5D/g' -e 's/!/%21/g')

  local url="https://uptime.noxs.me/api/push/${kuma_key}?status=${status}&msg=${encoded_msg}&ping="

  if ! curl -fsS "$url" >/dev/null; then
    echo "⚠️  Uptime Kuma notification failed (status: $status, msg: $msg)" >&2
  else
    echo "📬 Uptime Kuma notified: $status - $msg"
  fi
}

# -------------------------------
# Rclone Sync
# -------------------------------
echo "🔁 Starting Beltex sync process..."
rclone sync beltex: /media/sps_local/ \
  --config /opt/rclone/rclone.conf \
  --progress \
  --log-file /var/log/beltex/bc_beltex_sync.log \
  --log-format "date,time" \
  --log-level ERROR

if [ $? -eq 0 ]; then
  echo "✅ Sharepoint data successfully synced."
  BCK_SPS="ok"
  notify_kuma "$KUMA_KEY_RCLONE" "up" "Sharepoint sync OK"
else
  echo "❌ Sharepoint data sync failed!"
  notify_kuma "$KUMA_KEY_RCLONE" "down" "Sharepoint sync failed"
fi

# -------------------------------
# SPS PBS Backup
# -------------------------------
if [[ "$BCK_SPS" == "ok" ]]; then
  echo "💾 Backing up SPS to PBS..."
  if "$(dirname "$0")/bck_main.sh" --src="/media/sps_local" --dst="sps_local" --kuma-key="$KUMA_KEY_SPS"; then
    echo "✅ SPS backup successful."
    BCK_PBS_SPS="ok"
  else
    echo "❌ SPS backup failed!"
  fi
fi

# -------------------------------
# Luca PBS Backup
# -------------------------------
echo "💾 Backing up Luca to PBS..."
if "$(dirname "$0")/bck_main.sh" --src="/srv/beltex/Luca_Install" --dst="luca" --kuma-key="$KUMA_KEY_LUCA"; then
  echo "✅ Luca backup successful."
  BCK_PBS_LUCA="ok"
else
  echo "❌ Luca backup failed!"
fi

# -------------------------------
# Final Status Check
# -------------------------------
if [[ "$BCK_PBS_SPS" == "ok" && "$BCK_PBS_LUCA" == "ok" ]]; then
  echo "✅ All backups completed successfully."
  exit 0
else
  echo "❌ One or more backups failed."
  exit 1
fi