#!/bin/bash
# Fix NFS mounts on ZimaOS — both library shares
# Run: bash /tmp/fix-zimaos-nfs.sh
# You'll be prompted for sudo password once

set -e

echo "=== Step 1: Grant passwordless sudo for mount/umount ==="
echo "dtoro ALL=(ALL) NOPASSWD: /usr/sbin/mount.nfs, /usr/sbin/umount.nfs, /bin/mount, /bin/umount, /usr/bin/mount" | sudo tee /etc/sudoers.d/zimaos-nfs > /dev/null
sudo chmod 440 /etc/sudoers.d/zimaos-nfs
echo "  ✓ sudoers drop-in created"

echo "=== Step 2: Mount library from hubris (nfs-export LXC) ==="
sudo mkdir -p /media/library
sudo mount -t nfs -o nfsvers=4,rw,hard,intr 192.168.8.200:/mnt/library /media/library
echo "  ✓ /media/library ← 192.168.8.200:/mnt/library"

echo "=== Step 3: Mount ludo-library from strong ==="
sudo mkdir -p /media/ludo-library
sudo mount -t nfs -o nfsvers=4,rw,hard,intr 192.168.8.241:/mnt/media_local /media/ludo-library
echo "  ✓ /media/ludo-library ← 192.168.8.241:/mnt/media_local"

echo "=== Step 4: Verify ==="
echo ""
df -h | grep -E 'nfs|192.168'
echo ""
echo "--- /media/library contents ---"
ls /media/library/ | head -10
echo ""
echo "--- /media/ludo-library contents ---"
ls /media/ludo-library/ | head -10

echo ""
echo "=== Step 5: Persistent systemd mount units ==="

# Library mount unit
sudo tee /etc/systemd/system/media-library.mount > /dev/null << 'MOUNTUNIT'
[Unit]
Description=Mount nfs-export:/mnt/library as library
After=network-online.target
Wants=network-online.target

[Mount]
What=192.168.8.200:/mnt/library
Where=/media/library
Type=nfs
Options=nfsvers=4,rw,hard,intr

[Install]
WantedBy=multi-user.target
MOUNTUNIT

# Ludo-library mount unit
sudo tee /etc/systemd/system/media-ludo\x2dlibrary.mount > /dev/null << 'MOUNTUNIT2'
[Unit]
Description=Mount strong:/mnt/media_local as ludo-library
After=network-online.target
Wants=network-online.target

[Mount]
What=192.168.8.241:/mnt/media_local
Where=/media/ludo-library
Type=nfs
Options=nfsvers=4,rw,hard,intr

[Install]
WantedBy=multi-user.target
MOUNTUNIT2

sudo systemctl daemon-reload
sudo systemctl enable media-library.mount
sudo systemctl enable media-ludo\x2dlibrary.mount
echo "  ✓ Both systemd mount units created and enabled"

echo ""
echo "=== DONE ==="
echo "Both NFS mounts active and persistent across reboots:"
echo "  /media/library     ← 192.168.8.200:/mnt/library (hubris nfs-export LXC)"
echo "  /media/ludo-library ← 192.168.8.241:/mnt/media_local (strong)"