#!/usr/bin/env bash

# REFERENCES:
# https://help.ubuntu.com/community/NFSv4Howto
# https://www.ibm.com/docs/en/ftmfm/4.0.5?topic=offering-network-file-system-nfs-version-4

# Function to display an error message and exit the script
exit_with_error() {
    echo "Error: $1"
    exit 1
}

# Function to validate if the given directory path exists
validate_directory() {
    if [[ ! -d "$1" ]]; then
        exit_with_error "Directory '$1' does not exist."
    fi
}

# Function to validate if the given file exists
validate_file() {
    if [[ ! -f "$1" ]]; then
        exit_with_error "File '$1' does not exist."
    fi
}

# Function to restart NFS server
restart_nfs_server() {
    sudo service nfs-server restart
    sudo exportfs -ra
}

mkdir -p "$HOME/data/share_nfs"
read -p "Enter the directory path you want to share [default: ~/data/share_nfs] : " share_path
share_path=${share_path:-$HOME/data/share_nfs}
validate_directory "$share_path"
validate_file "/etc/exports"

# Generate the NFS export line with default options
export_line="$share_path *(rw,sync,fsid=0,no_subtree_check,crossmnt,no_root_squash,insecure)"
# for wsl, remember to add insecure option to /etc/exportfs file on server side

# Add the export line to the /etc/exports file
echo "$export_line" | sudo tee -a /etc/exports >/dev/null

restart_nfs_server

echo "NFS sharing configured successfully!"

