#!/usr/bin/env bash

set -euo pipefail

REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
FSTAB_FRAGMENT="$REPO_DIR/smb/fstab.fragment"

echo "Installing SMB support..."
yay -S --needed --noconfirm cifs-utils smbclient

if [[ ! -f "$FSTAB_FRAGMENT" ]]; then
    echo "No smb/fstab.fragment found. Copy smb/fstab.fragment.example and edit it first."
    exit 0
fi

while read -r device mountpoint rest; do
    [[ -n "${device:-}" ]] || continue
    [[ "$device" != \#* ]] || continue
    [[ -n "${mountpoint:-}" ]] || continue

    sudo mkdir -p "$mountpoint"

    if ! grep -Fq "$device $mountpoint " /etc/fstab; then
        echo "$device $mountpoint $rest" | sudo tee -a /etc/fstab >/dev/null
        echo "Added fstab entry for $mountpoint"
    else
        echo "fstab already contains $mountpoint"
    fi
done < "$FSTAB_FRAGMENT"

sudo systemctl daemon-reload
echo "SMB setup complete."
