#!/bin/bash

###############################################################################
# Configuration Section
###############################################################################
# Server 1 Configuration
SERVER1_SSH_USER="root"
SERVER1_SSH_SERVER="bethaus-speyer.de"
SERVER1_SSH_SERVER_PORT=1122          # Remote SSH server port for Server 1
SERVER1_REMOTE_NFS_PORT=2049          # Remote NFS server port (usually 2049)
SERVER1_LOCAL_PORT_BASE=2022          # Base local port for SSH tunnel (will add index offset)

# Define multiple mount configurations for Server 1
# Each index corresponds to a mount point and NFS share.
SERVER1_MOUNT_POINTS=(
    "/mnt/Gottesdienste Speyer"
    "/mnt/Besondere Gottesdienste"
    "/mnt/Liedersammlung"
    "/mnt/app_share"
)
SERVER1_NFS_SHARES=(
    "/volume1/Aufnahme-stereo/010 Gottesdienste ARCHIV"
    "/volume1/Aufnahme-stereo/013 Besondere Gottesdienste"
    "/volume1/Aufnahme-stereo/014 Liedersammlung"
    "/volume1/app_share"
)

# Server 2 Configuration
SERVER2_SSH_USER="root"
SERVER2_SSH_SERVER="bethaus-schwegenheim.de"
SERVER2_SSH_SERVER_PORT=1122         # Remote SSH server port for Server 2
SERVER2_REMOTE_NFS_PORT=2049         # Remote NFS server port
SERVER2_LOCAL_PORT_BASE=3022         # Base local port for SSH tunnel (will add index offset)

# Define multiple mount configurations for Server 2
SERVER2_MOUNT_POINTS=(
    "/mnt/Gottesdienste Schwegenheim"
)
SERVER2_NFS_SHARES=(
    "/volume1/Aufnahme-stereo/010 Gottesdienste ARCHIV"
)

# List of server identifiers (must match the prefix of configuration variables)
SERVERS=("SERVER1" "SERVER2")

###############################################################################
# Function Definitions
###############################################################################

# Check if the SSH tunnel on a given local port is active
is_tunnel_active() {
    local port=$1
    timeout 1 bash -c "</dev/tcp/localhost/${port}" &>/dev/null
}

# Check if the given mount point is currently mounted
is_nfs_mounted() {
    local mount_point=$1
    mount | grep -q "${mount_point}"
}

###############################################################################
# Main Loop: Process Each Server and Its Mount Points
###############################################################################
for server in "${SERVERS[@]}"; do
    # Retrieve server-specific configuration using indirect expansion
    ssh_user_var="${server}_SSH_USER"
    ssh_server_var="${server}_SSH_SERVER"
    ssh_server_port_var="${server}_SSH_SERVER_PORT"
    remote_nfs_port_var="${server}_REMOTE_NFS_PORT"
    local_port_base_var="${server}_LOCAL_PORT_BASE"
    mount_points_var="${server}_MOUNT_POINTS[@]"
    nfs_shares_var="${server}_NFS_SHARES[@]"

    SSH_USER="${!ssh_user_var}"
    SSH_SERVER="${!ssh_server_var}"
    SSH_SERVER_PORT="${!ssh_server_port_var}"
    REMOTE_NFS_PORT="${!remote_nfs_port_var}"
    LOCAL_PORT_BASE="${!local_port_base_var}"
    MOUNT_POINTS=("${!mount_points_var}")
    NFS_SHARES=("${!nfs_shares_var}")

    echo "-------------------------------------------------"
    echo "[INFO] Processing server: ${SSH_SERVER}"

    # Loop over each mount configuration for the current server.
    for i in "${!MOUNT_POINTS[@]}"; do
        MOUNT_POINT="${MOUNT_POINTS[$i]}"
        NFS_SHARE="${NFS_SHARES[$i]}"
        # Calculate a unique local port: base + index offset
        LOCAL_PORT=$(( LOCAL_PORT_BASE + i ))

        echo "-------------------------------------------------"
        echo "[INFO] Setting up mount for ${MOUNT_POINT}"
        echo "[INFO] NFS Share: ${NFS_SHARE}"
        echo "[INFO] Using local port: ${LOCAL_PORT}"

        # Check and (re)establish the SSH tunnel if needed.
        if ! is_tunnel_active "${LOCAL_PORT}"; then
            echo "[INFO] SSH Tunnel on port ${LOCAL_PORT} is down. Attempting to reconnect..."
            ssh -f -N -L "${LOCAL_PORT}:localhost:${REMOTE_NFS_PORT}" \
                -o ExitOnForwardFailure=yes \
                -p "${SSH_SERVER_PORT}" \
                "${SSH_USER}@${SSH_SERVER}"

            if is_tunnel_active "${LOCAL_PORT}"; then
                echo "[SUCCESS] SSH Tunnel established on local port ${LOCAL_PORT}."
            else
                echo "[ERROR] Failed to establish SSH tunnel for mount ${MOUNT_POINT}!"
                continue  # Skip mounting for this configuration if tunnel fails
            fi
        else
            echo "[INFO] SSH Tunnel already active on port ${LOCAL_PORT}."
        fi

        # Ensure the mount point directory exists
        if [ ! -d "${MOUNT_POINT}" ]; then
            echo "[INFO] Creating mount point directory: ${MOUNT_POINT}"
            sudo mkdir -p "${MOUNT_POINT}"
        fi

        # Mount the NFS share if it's not already mounted.
        if ! is_nfs_mounted "${MOUNT_POINT}"; then
            echo "[INFO] NFS share is not mounted at ${MOUNT_POINT}. Attempting to mount..."
            sudo mount -t nfs -o port="${LOCAL_PORT}",nolock,soft 127.0.0.1:"${NFS_SHARE}" "${MOUNT_POINT}"
            if is_nfs_mounted "${MOUNT_POINT}"; then
                echo "[SUCCESS] NFS share mounted successfully at ${MOUNT_POINT}."
            else
                echo "[ERROR] Failed to mount NFS share ${NFS_SHARE} at ${MOUNT_POINT}!"
            fi
        else
            echo "[INFO] NFS share is already mounted at ${MOUNT_POINT}."
        fi

    done
done
echo "-------------------------------------------------"
echo "[INFO] All server mount configurations processed."
