#!/bin/bash
#
# deploy-comfyui-sync — Push sync-comfyui-snaps and dependencies to nimo.loc
# and configure cron, credentials, and sudoers.
#
# Run this from your Mac (from the schmeeve-toolz repo root):
#   ./deploy-comfyui-sync

set -euo pipefail

NIMO="schmeeve@nimo.loc"
REMOTE_BIN="/home/schmeeve/.local/bin"
REMOTE_LOG="/home/schmeeve/.local/log"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"

SCRIPTS=(
  sync-comfyui-snaps
  rename-ai-snaps
  organize-images
  extract-ai-meta
)

echo "[deploy] Deploying to ${NIMO}"

# 1. Ensure remote dirs exist
ssh "${NIMO}" "mkdir -p ${REMOTE_BIN} ${REMOTE_LOG} ~/.smb"

# 2. Copy scripts
echo "[deploy] Copying scripts → ${REMOTE_BIN}/"
for s in "${SCRIPTS[@]}"; do
  src="${SCRIPT_DIR}/${s}"
  if [ ! -f "${src}" ]; then
    echo "[deploy] WARNING: ${src} not found, skipping"
    continue
  fi
  scp -q "${src}" "${NIMO}:${REMOTE_BIN}/${s}"
  echo "  ✓ ${s}"
done

# 3. Make scripts executable
ssh "${NIMO}" "chmod +x $(printf "${REMOTE_BIN}/%s " "${SCRIPTS[@]}")"

# 4. Install Python dependency (Pillow) for rename-ai-snaps and extract-ai-meta
echo "[deploy] Installing Pillow (Python)"
ssh "${NIMO}" "pip3 install --user --quiet Pillow && echo '  ✓ Pillow installed'"

# 5. Create NAS credentials file template if not already present
echo "[deploy] Checking NAS credentials file"
ssh "${NIMO}" '
  if [ -f ~/.smb/mini.nas ]; then
    echo "  credentials file already exists, skipping"
  else
    printf "username=schmeeve\npassword=CHANGEME\n" > ~/.smb/mini.nas
    chmod 600 ~/.smb/mini.nas
    echo "  created ~/.smb/mini.nas — EDIT IT to set your NAS password"
  fi
'

# 6. Add sudoers entry for passwordless cifs mount
echo "[deploy] Configuring sudoers for cifs mount"
ssh -t "${NIMO}" '
  SUDOERS_FILE="/etc/sudoers.d/schmeeve-cifs"
  RULE="schmeeve ALL=(root) NOPASSWD: /usr/bin/mount -t cifs *"
  if sudo test -f "${SUDOERS_FILE}" 2>/dev/null; then
    echo "  sudoers entry already exists"
  else
    echo "${RULE}" | sudo tee "${SUDOERS_FILE}" > /dev/null
    sudo chmod 440 "${SUDOERS_FILE}"
    echo "  sudoers entry added: ${SUDOERS_FILE}"
  fi
'

# 7. Create mount point
ssh "${NIMO}" "mkdir -p /home/schmeeve/mnt/miniShare1"

# 8. Add cron job (every 2 hours) if not already present
echo "[deploy] Checking crontab"
ssh "${NIMO}" '
  CRON_LINE="0 */2 * * * /home/schmeeve/.local/bin/sync-comfyui-snaps >> /home/schmeeve/.local/log/sync-comfyui-snaps.log 2>&1"
  if crontab -l 2>/dev/null | grep -qF "sync-comfyui-snaps"; then
    echo "  cron entry already exists"
  else
    ( crontab -l 2>/dev/null; echo "${CRON_LINE}" ) | crontab -
    echo "  cron entry added (every 2 hours)"
  fi
'

echo
echo "[deploy] Done."
echo
echo "  Next step: if ~/.smb/mini.nas still has CHANGEME, SSH in and set your NAS password:"
echo "    ssh ${NIMO}"
echo "    nano ~/.smb/mini.nas"
echo
echo "  Test the sync manually:"
echo "    ssh ${NIMO} ${REMOTE_BIN}/sync-comfyui-snaps"
