#!/bin/bash
set -euo pipefail

# --- Configuration ---
PORT="${1:-}"
QB_HOST="http://localhost:8080"
QB_USER="admin"
QB_PASS="Vocalize_Void_Rage_Visor_Ladies_Undercook_Spokesman_Fraternal"
LOG_DIR="/pia-shared/logs"
LOG_FILE="$LOG_DIR/update_port.log"
MAX_LOG_SIZE=$((1024 * 1024))  # 1 MiB
TIMESTAMP="$(date '+%F %T')"

# --- Rotation des logs ---
rotate_log() {
  if [[ -f "$LOG_FILE" && $(stat -c%s "$LOG_FILE") -gt $MAX_LOG_SIZE ]]; then
    echo "$TIMESTAMP ℹ️ Log file too big, rotating..." >> "$LOG_FILE"
    for i in {4..1}; do
      [[ -f "$LOG_FILE.$((i-1))" ]] && mv "$LOG_FILE.$((i-1))" "$LOG_FILE.$i"
    done
    mv "$LOG_FILE" "$LOG_FILE.1"
    touch "$LOG_FILE"
  fi
}
rotate_log

# --- Validation du port ---
if [[ -z "$PORT" || ! "$PORT" =~ ^[0-9]+$ ]]; then
  echo "$TIMESTAMP ❌ Port manquant ou invalide: '$PORT'" >> "$LOG_FILE"
  exit 1
fi

# --- Attente de disponibilité de qBittorrent ---
MAX_WAIT=60  # secondes
DELAY=2
WAITED=0
while ! curl -fs --max-time 2 "$QB_HOST/api/v2/app/version" >/dev/null; do
  if [[ "$WAITED" -ge "$MAX_WAIT" ]]; then
    echo "$TIMESTAMP ❌ qBittorrent non disponible après $MAX_WAIT secondes." >> "$LOG_FILE"
    exit 2
  fi
  sleep "$DELAY"
  WAITED=$((WAITED + DELAY))
done
echo "$TIMESTAMP ✅ qBittorrent disponible après $WAITED secondes." >> "$LOG_FILE"

# --- Authentification ---
COOKIE_JAR=$(mktemp)
RESPONSE=$(curl -fsSL -c "$COOKIE_JAR" \
  --header "Referer: $QB_HOST" \
  --data "username=$QB_USER&password=$QB_PASS" \
  "$QB_HOST/api/v2/auth/login")

if [[ "$RESPONSE" != "Ok." ]]; then
  echo "$TIMESTAMP ❌ Authentification échouée : $RESPONSE" >> "$LOG_FILE"
  rm -f "$COOKIE_JAR"
  exit 3
fi

# --- Lire le port actuel ---
RAW_JSON=$(curl -fsSL -b "$COOKIE_JAR" "$QB_HOST/api/v2/app/preferences")
CURRENT_PORT=$(echo "$RAW_JSON" | grep -o '"listen_port":[0-9]*' | sed 's/[^0-9]*//')

if [[ "$CURRENT_PORT" == "$PORT" ]]; then
  echo "$TIMESTAMP ℹ️ Port déjà configuré sur $PORT, aucune mise à jour nécessaire." >> "$LOG_FILE"
  rm -f "$COOKIE_JAR"
  exit 0
fi

# --- Mise à jour du port ---
RESULT=$(curl -fsSL -b "$COOKIE_JAR" \
  --data-urlencode "json={\"listen_port\":$PORT}" \
  "$QB_HOST/api/v2/app/setPreferences")

rm -f "$COOKIE_JAR"

echo "$TIMESTAMP ✅ Port mis à jour de $CURRENT_PORT → $PORT. Réponse : $RESULT" >> "$LOG_FILE"
exit 0