#!/usr/bin/fish

echo "Starting CachyOS setup..."

# Ask for sudo ONCE at the start
echo "Please enter your password once to authorise setup:"
sudo -v; or exit 1

echo "Authorised. Continuing..."

# Update system
echo "Updating system..."
sudo pacman -Syu --noconfirm; or exit 1

# Install yay if needed (AUR helper)
if not command -v yay >/dev/null
    echo "Installing yay..."
    sudo pacman -S --needed --noconfirm base-devel git; or exit 1
    cd /tmp
    git clone https://aur.archlinux.org/yay.git; or exit 1
    cd yay
    makepkg -si --noconfirm; or exit 1
    cd ..
    rm -rf yay
else
    echo "yay already installed, skipping"
end

# Pacman packages (core and productivity apps)
echo "Installing pacman packages..."
sudo pacman -S --needed --noconfirm \
    nfs-utils rclone gparted kdenlive gimp kid3 okular \
    timeshift vlc libreoffice-fresh \
    libreoffice-fresh-en-gb hunspell-en_gb nextcloud; or exit 1

# AUR packages (extra/user apps)
echo "Installing AUR packages..."
yay -S --needed --noconfirm \
    rustdesk-bin ventoy-bin brave-bin beeper-v4-bin \
    mediawriter onlyoffice-bin clipgrab megasync \
    bitwarden-bin eddie-ui notepadnext-bin screamingfrogseospider upscayl-bin \
    betterbird-bin; or exit 1

# NFS services
echo "Configuring NFS..."
sudo systemctl enable --now rpcbind nfs-client.target

# Generic media mount
sudo mkdir -p /mnt/media

# Add NFS entry to fstab if not present
if not grep -q "Media" /etc/fstab
    echo "192.168.0.5:/mnt/array1/Media /mnt/media nfs defaults 0 0" \
        | sudo tee -a /etc/fstab
end

# Mount all filesystems
sudo mount -a

# Verify NFS mount
echo "Verifying NFS mounts..."
mountpoint /mnt/media; and echo "✅ Media mount OK" or echo "❌ Media mount failed"

# Enable automatic update checks and tray icon
echo "Enabling automatic update notifications..."
systemctl --user enable --now arch-update.timer
arch-update --tray --enable

# Clean up package caches
echo "Cleaning up package caches..."
sudo pacman -Sc --noconfirm
yay -Sc --noconfirm

echo "✅ Setup complete."