#!/bin/bash
# Knight Rider S01 1080p Upgrade - Scheduled 2026-05-27 13:19 UTC
set -e

SSH_CMD="ssh -o StrictHostKeyChecking=no -i /root/.ssh/id_ed25519 root@192.168.8.112"
SRC='/mnt/Main/martin/truenas-docker/jdownloader2/output/Knight.Rider.S01.German.DTSHD.DL.FS.1080p.BluRay.x264-QfG - serienfans.org'
DST='/mnt/Main/Filme/Krimi/Knight Rider (1982)/Season 01'
LOG="/tmp/knight-rider-upgrade-$(date +%Y%m%d-%H%M%S).log"

exec > >(tee "$LOG") 2>&1

echo "=== $(date -u) Knight Rider 1080p Upgrade START ==="

# 1. Copy all missing mkvs to Season 01
echo "--- Step 1: Copy missing mkvs ---"
$SSH_CMD "find '$SRC' -name '*.mkv' | while read f; do
  base=\$(basename \"\$f\")
  if [ ! -f '$DST/\$base' ]; then
    echo \"COPYING: \$base\"
    cp -v \"\$f\" '$DST/'
  else
    echo \"EXISTS: \$base\"
  fi
done"

# 2. Rename 1080p files to match Season 2-4 naming (Knight Rider - S01EXX - Title.mkv)
echo "--- Step 2: Rename to standard naming ---"
$SSH_CMD "cd '$DST' && for f in Knight.Rider.40th.Ann.*.mkv; do
  [ -f \"\$f\" ] || continue
  base=\$(basename \"\$f\" .mkv)
  ep_part=\$(echo \"\$base\" | grep -oP 'S01E[0-9]+E?[0-9]*')
  title=\$(echo \"\$base\" | sed 's/Knight\.Rider\.40th\.Ann\.S01E[0-9]*E\?[0-9]*\.//' | sed 's/\.German\.DTSHD.*//')
  title_nice=\$(echo \"\$title\" | tr '.' ' ' | sed 's/ae/ä/g; s/oe/ö/g; s/ue/ü/g; s/Ae/Ä/g; s/Oe/Ö/g; s/Ue/Ü/g; s/ss$/ß/g')
  newname=\"Knight Rider - \${ep_part} - \${title_nice}.mkv\"
  if [ ! -f \"\$newname\" ] && [ -f \"\$f\" ]; then
    echo \"RENAME: \$f -> \$newname\"
    mv \"\$f\" \"\$newname\"
  else
    echo \"SKIP: \$f (target exists or source gone)\"
  fi
done"

# 3. List final result
echo "--- Step 3: Final file list ---"
$SSH_CMD "ls -lh '$DST/'*.mkv"

echo "=== $(date -u) Knight Rider 1080p Upgrade DONE ==="

# 4. Notify Martin via OpenClaw
# The sub-agent will handle the notification
