#!/bin/bash
set -euo pipefail

# Script to mount multiple CIFS shares and handle credentials separately per mount
# Compatible with Ubuntu, Debian, RHEL, CentOS, Fedora, AlmaLinux

# Detect OS type
detect_os() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        echo "Detected OS: $NAME ($ID)"
        OS=$ID
    else
        echo "Unsupported OS"
        exit 1
    fi
}

# Install CIFS utilities
install_cifs_utils() {
    echo "Installing CIFS utilities..."
    if [[ "$OS" == "ubuntu" || "$OS" == "debian" ]]; then
        apt-get update -y
        apt-get install -y cifs-utils samba
    elif [[ "$OS" == "rhel" || "$OS" == "centos" || "$OS" == "fedora" || "$OS" == "almalinux" ]]; then
        yum update -y
        yum install -y cifs-utils samba
    else
        echo "Unsupported OS"
        exit 1
    fi
}

# Prompt user for multiple CIFS mount inputs
handle_mounts() {
    while true; do
        echo
        read -p "Enter the CIFS share address (e.g., //server/share): " cifs_share
        read -p "Enter the mount point directory (default: /mnt/media): " mount_point
        mount_point=${mount_point:-/mnt/media}

        mkdir -p "$mount_point"

        read -p "Enter the username: " username
        read -sp "Enter the password: " password
        echo

        cred_file="/etc/samba/credentials_$(basename "$mount_point")"
        echo -e "username=$username\npassword=$password" > "$cred_file"
        chmod 600 "$cred_file"
        echo "Credentials stored at $cred_file"

        echo "Mounting $cifs_share at $mount_point..."

        # Try SMB 3.0 first
        if ! mount -t cifs "$cifs_share" "$mount_point" \
            -o credentials="$cred_file",vers=3.0,iocharset=utf8,uid=1000,gid=1000,file_mode=0660,dir_mode=0770; then
            echo "SMB 3.0 failed, retrying with SMB 3.1.1..."
            if ! mount -t cifs "$cifs_share" "$mount_point" \
                -o credentials="$cred_file",vers=3.1.1,iocharset=utf8,uid=1000,gid=1000,file_mode=0660,dir_mode=0770; then
                echo "❌ Failed to mount $cifs_share, please check credentials or network."
                exit 1
            fi
        fi

        echo "✅ Mounted successfully."

        read -p "Add this mount to /etc/fstab for automount at boot? (y/n): " add_fstab
        if [[ "$add_fstab" =~ ^[Yy]$ ]]; then
            fstab_entry="$cifs_share $mount_point cifs credentials=$cred_file,vers=3.0,iocharset=utf8,uid=1000,gid=1000,file_mode=0660,dir_mode=0770 0 0"
            if ! grep -qsF "$fstab_entry" /etc/fstab; then
                echo "$fstab_entry" >> /etc/fstab
                echo "Added to /etc/fstab"
            else
                echo "Entry already exists in /etc/fstab"
            fi
        fi

        read -p "Do you want to add another CIFS mount? (y/n): " more
        [[ "$more" =~ ^[Yy]$ ]] || break
    done
}

# Main execution
detect_os
install_cifs_utils
handle_mounts

echo "🎉 All operations completed."
