#!/bin/bash
# Remount Synology share with permissive options + restart doc-ingest
set -euo pipefail
PASS="${NAS_PASS:-Foodlinkk#2026}"
FSTAB_ENTRY='//10.4.7.11/share /mnt/synology cifs credentials=/etc/smbcredentials/synology,vers=3.0,uid=1000,gid=1000,file_mode=0775,dir_mode=0775,_netdev 0 0'

fix_host() {
  local host="$1"
  echo "==> Fix NAS mount on $host"
  sshpass -p "$PASS" ssh -o StrictHostKeyChecking=no "aissa@$host" "PASS='$PASS' FSTAB_ENTRY='$FSTAB_ENTRY' bash -s" <<'REMOTE'
set -e
echo "$PASS" | sudo -S mkdir -p /etc/smbcredentials /mnt/synology
if [ ! -f /etc/smbcredentials/synology ]; then
  echo "$PASS" | sudo -S bash -c "printf '%s\n' 'username=aissa' 'password=$PASS' > /etc/smbcredentials/synology"
  echo "$PASS" | sudo -S chmod 600 /etc/smbcredentials/synology
fi
echo "$PASS" | sudo -S sed -i '/10\.4\.7\.11\/share/d' /etc/fstab
echo "$PASS" | sudo -S bash -c "echo '$FSTAB_ENTRY' >> /etc/fstab"
echo "$PASS" | sudo -S umount /mnt/synology 2>/dev/null || true
echo "$PASS" | sudo -S mount /mnt/synology
echo "Share files: $(find /mnt/synology -type f ! -path '*#recycle*' 2>/dev/null | wc -l)"
echo "CUCINA files: $(find /mnt/synology/CUCINA -type f 2>/dev/null | wc -l)"
REMOTE
}

fix_host "10.4.7.19"
fix_host "10.4.7.18"

echo "==> Restart doc-ingest"
sshpass -p "$PASS" ssh -o StrictHostKeyChecking=no aissa@10.4.7.19 \
  'cd ~/foodlinkk-ai/doc-ingest && docker compose restart 2>/dev/null || docker restart foodlinkk-doc-ingest'

echo "==> Done"
echo "Als CUCINA/Foodlinkk nog 0 bestanden tonen: Synology DSM -> share -> Permissions -> aissa Read/Write + submappen"
