#!/usr/bin/env bash


# write a bash script to do automount of nfs share:
# prompt user for remote server and nfs shares folder in format name:/path
# prompt user for mounting location, if user pressed enter as a skip, then share should be mounted at a similar corresponding location in the local machine.
# add a line to fstab file to ensure autmount.
# add as much checkpoints as you can to ensure extremely rigorous code that works under all circumstances, e.g. before changing fstab file, ensure that the line to be added is not there already etc.
# Also be extremely verbose to delineate what you are doing by echoing to the terminal

# mount nfs share on linux
# sudo apt install nfs-common
# mkdir ~/data/local
# sudo mount -o nolock,noatime,nodiratime,proto=tcp,timeo=600,retrans=2,noac alex-p51s-5:/home/alex/data/local ./data/local


op_script=$HOME/tmp_results/shells/python_return_command.sh
if [ -f "$op_script" ]; then
  rm $op_script
fi
. activate_ve
python -m machineconfig.scripts.python.mount_nfs
#source $HOME/tmp_results/shells/python_return_command.sh
if [ -f "$op_script" ]; then
  chmod +x $op_script
  source $op_script
fi

# Check if remote server is reachable and share folder exists
if ! ping -c 1 "$remote_server" &> /dev/null; then
  echo "💥 Error: Remote server $remote_server is not reachable."
  exit 1
fi

#if ! showmount -e "$remote_server" | grep -q "$share_path"; then
#  echo "Error: NFS share folder $share_path is not available on $remote_server."
#  exit 1
#fi

# Check if the share is already mounted
if mount | grep -q ":$share_path on "; then
  echo "⚠️ The NFS share $share_info is already mounted."
  exit 0
fi


if [ ! -d "$local_mount_point" ]; then
  echo "➡️ Creating local mount point directory $local_mount_point"
  sudo mkdir -p "$local_mount_point"
  sudo chown "$(id -u):$(id -g)" "$local_mount_point"
fi

sudo service rpcbind start
sudo service nfs-common start
# without the two above, on wsl, you get error: https://superuser.com/questions/657071/mount-nfs-rpc-statd-is-not-running-but-is-required-for-remote-locking

echo "💡 Mounting NFS share $share_info at $local_mount_point using command:"
echo "sudo mount -t nfs $share_info $local_mount_point"
sudo mount -t nfs "$share_info" "$local_mount_point"

# Add a line to fstab file to ensure automount
fstab_line="$remote_server:$share_path $local_mount_point nfs defaults 0 0"
if grep -qF "$fstab_line" /etc/fstab; then
  echo "🤷‍♂️ The following line already exists in /etc/fstab:"
  echo "$fstab_line"
else
  echo "➡️ Adding the following line to /etc/fstab:"
  echo "$fstab_line"
  echo "$fstab_line" | sudo tee -a /etc/fstab > /dev/null
fi
