#!/usr/bin/env bash

# This script mounts the NFS share for the Sens 001 files on the IC NAS1 server.
# The script is intended to be run on a Debian-based system.
# The script will install the nfs-common package if it is not already installed.
# The script will create the mount point if it does not exist.
# The script will mount the NFS share if it is not already mounted.

set -e # Exit on error
set -o pipefail # Exit on pipe error
set -u # Fail on unset variables

MOUNT_POINT="/mnt/sens_001_files_nfs"
NFS_SERVER="ic-nas1-nfs.rcp.epfl.ch"
NFS_PATH="/ic/u1241_sens/sens_001_files_nfs"
NFS_OPTIONS="defaults"

# Check that the mount point is not already mounted
if mountpoint -q "$MOUNT_POINT"; then
    echo "NFS share already mounted at $MOUNT_POINT"
    exit 0
fi

# Check that the OS supports dpkg
if ! command -v dpkg &> /dev/null; then
    echo "This script is only supported on Debian-based systems"
    exit 1
fi

# install the nfs-common package
sudo apt-get update
sudo apt-get install -y nfs-common

# Create the mount point if it does not exist
if [ ! -d "$MOUNT_POINT" ]; then
    mkdir -p "$MOUNT_POINT"
fi

# Mount the NFS share
if ! mountpoint -q "$MOUNT_POINT"; then
    sudo mount -t nfs -o "$NFS_OPTIONS" "$NFS_SERVER":"$NFS_PATH" "$MOUNT_POINT"
fi

# Print the mount status
mountpoint -q "$MOUNT_POINT" && echo "NFS share mounted at $MOUNT_POINT" || echo "Failed to mount NFS share at $MOUNT_POINT"

# Inform the user that the mount is not permanent. The user may be willing to make it permanent by adding an entry to /etc/fstab
echo "*****************************************************************************************************"
echo "Notes:"
echo "You may want to unmount the NFS share by running 'sudo umount $MOUNT_POINT'"
echo ""
echo "The NFS share is not mounted permanently. To make it permanent, add the following line to /etc/fstab:"
echo "$NFS_SERVER:$NFS_PATH $MOUNT_POINT nfs $NFS_OPTIONS 0 0"
echo "*****************************************************************************************************"
