#!/bin/bash

# NAS Mount Setup Script for Fedora 42
# This script helps set up persistent mounting of your NAS at 192.168.68.51

set -e

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Configuration
NAS_IP="192.168.68.51"
MOUNT_POINT="/mnt/share/media"
CREDENTIALS_FILE="/etc/nas-credentials"
FSTAB_BACKUP="/etc/fstab.backup.$(date +%Y%m%d_%H%M%S)"

# Logging functions
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if running as root
check_root() {
    if [[ $EUID -eq 0 ]]; then
        log_error "This script should not be run as root. Please run as a regular user."
        log_info "The script will use sudo when needed."
        exit 1
    fi
}

# Check prerequisites
check_prerequisites() {
    log_info "Checking prerequisites..."

    # Check if required packages are installed
    if ! rpm -q cifs-utils >/dev/null 2>&1; then
        log_error "cifs-utils package is not installed"
        log_info "Install it with: sudo dnf install cifs-utils"
        exit 1
    fi

    if ! rpm -q nfs-utils >/dev/null 2>&1; then
        log_error "nfs-utils package is not installed"
        log_info "Install it with: sudo dnf install nfs-utils"
        exit 1
    fi

    # Check network connectivity
    if ! ping -c 1 "$NAS_IP" >/dev/null 2>&1; then
        log_error "Cannot reach NAS at $NAS_IP"
        exit 1
    fi

    log_success "All prerequisites met"
}

# Test SMB shares
test_smb_shares() {
    log_info "Testing SMB shares on $NAS_IP..."

    # First try to get shares without credentials (guest access)
    log_info "Trying guest access first..."
    if smbclient -L "$NAS_IP" -N 2>/dev/null; then
        return 0
    fi

    log_info "Guest access failed. Authentication required."
    echo "Please enter your NAS username:"
    read -r username

    if [[ -n "$username" ]]; then
        echo "Enter password for $username:"
        read -rs password
        echo ""

        log_info "Listing SMB shares with authentication..."
        if smbclient -L "$NAS_IP" -U "$username%$password" 2>/dev/null; then
            # Store credentials for later use
            SMB_USERNAME="$username"
            SMB_PASSWORD="$password"
            return 0
        else
            log_warning "Authentication failed or no shares found"
            log_info "Please check your username and password"
            return 1
        fi
    else
        log_error "Username is required for this NAS"
        return 1
    fi
}

# Test NFS exports
test_nfs_exports() {
    log_info "Testing NFS exports on $NAS_IP..."

    local exports
    exports=$(showmount -e "$NAS_IP" 2>/dev/null)

    if [[ -n "$exports" ]]; then
        echo "$exports"
        return 0
    else
        log_warning "No NFS exports found or access denied"
        log_info "NFS exports are directory paths on the NAS that are shared via NFS protocol"
        log_info "Common examples: /volume1/media, /mnt/storage, /export/data"
        log_info "Your NAS appears to use SMB/CIFS instead of NFS"
        return 1
    fi
}

# Setup SMB mount
setup_smb_mount() {
    local share_name="$1"
    local username="$2"
    local password="$3"

    log_info "Setting up SMB mount for share: $share_name"

    # Create credentials file if authentication is needed
    if [[ -n "$username" ]]; then
        log_info "Creating credentials file at $CREDENTIALS_FILE"
        sudo tee "$CREDENTIALS_FILE" >/dev/null <<EOF
username=$username
password=$password
domain=WORKGROUP
EOF
        sudo chmod 600 "$CREDENTIALS_FILE"
        log_success "Credentials file created"

        # Test mount with credentials
        local mount_options="credentials=$CREDENTIALS_FILE,uid=$(id -u),gid=$(id -g),iocharset=utf8,file_mode=0644,dir_mode=0755"
    else
        # Guest access
        local mount_options="guest,uid=$(id -u),gid=$(id -g),iocharset=utf8,file_mode=0644,dir_mode=0755"
    fi

    # Test the mount
    log_info "Testing SMB mount..."
    if sudo mount -t cifs "//$NAS_IP/$share_name" "$MOUNT_POINT" -o "$mount_options"; then
        log_success "Test mount successful"
        sudo umount "$MOUNT_POINT"

        # Add to fstab
        setup_fstab_entry "cifs" "//$NAS_IP/$share_name" "$mount_options"
    else
        log_error "SMB mount test failed"
        return 1
    fi
}

# Setup NFS mount
setup_nfs_mount() {
    local export_path="$1"

    log_info "Setting up NFS mount for export: $export_path"

    local mount_options="rw,hard,intr,rsize=8192,wsize=8192,timeo=14"

    # Test the mount
    log_info "Testing NFS mount..."
    if sudo mount -t nfs "$NAS_IP:$export_path" "$MOUNT_POINT" -o "$mount_options"; then
        log_success "Test mount successful"
        sudo umount "$MOUNT_POINT"

        # Add to fstab
        setup_fstab_entry "nfs" "$NAS_IP:$export_path" "$mount_options"
    else
        log_error "NFS mount test failed"
        return 1
    fi
}

# Setup fstab entry
setup_fstab_entry() {
    local fs_type="$1"
    local device="$2"
    local options="$3"

    log_info "Setting up persistent mount in /etc/fstab"

    # Backup fstab
    sudo cp /etc/fstab "$FSTAB_BACKUP"
    log_info "Created fstab backup: $FSTAB_BACKUP"

    # Add entry to fstab
    local fstab_entry="$device $MOUNT_POINT $fs_type $options,noauto,user 0 0"

    # Check if entry already exists
    if grep -q "$MOUNT_POINT" /etc/fstab; then
        log_warning "Mount point already exists in fstab. Updating entry..."
        sudo sed -i "\|$MOUNT_POINT|d" /etc/fstab
    fi

    echo "$fstab_entry" | sudo tee -a /etc/fstab >/dev/null
    log_success "Added mount entry to fstab"

    # Create systemd mount unit for better boot integration
    create_systemd_mount_unit "$fs_type" "$device" "$options"
}

# Create systemd mount unit
create_systemd_mount_unit() {
    local fs_type="$1"
    local device="$2"
    local options="$3"

    local unit_name="mnt-share-media.mount"
    local unit_file="/etc/systemd/system/$unit_name"

    log_info "Creating systemd mount unit: $unit_name"

    sudo tee "$unit_file" >/dev/null <<EOF
[Unit]
Description=Mount NAS Media Share
After=network-online.target
Wants=network-online.target

[Mount]
What=$device
Where=$MOUNT_POINT
Type=$fs_type
Options=$options

[Install]
WantedBy=multi-user.target
EOF

    # Enable the mount unit
    sudo systemctl daemon-reload
    sudo systemctl enable "$unit_name"

    log_success "Systemd mount unit created and enabled"
}

# Interactive setup
interactive_setup() {
    log_info "=== NAS Mount Setup for $NAS_IP ==="
    echo ""

    echo "Choose your preferred mounting method:"
    echo "1) SMB/CIFS (recommended for Windows-based NAS)"
    echo "2) NFS (recommended for Linux-based NAS)"
    echo "3) Test both and let me choose"
    echo ""
    read -rp "Enter your choice (1-3): " choice

    case $choice in
        1)
            log_info "Setting up SMB/CIFS mount..."
            log_info "SMB shares are folder names shared by your NAS (like 'media', 'backup', 'public')"
            echo ""
            if test_smb_shares; then
                echo ""
                echo "Available SMB shares are listed above."
                read -rp "Enter the share name to mount (e.g., 'media' or 'public'): " share_name

                # Use credentials from test_smb_shares if available
                local username="${SMB_USERNAME:-}"
                local password="${SMB_PASSWORD:-}"

                # If no credentials from test, ask again
                if [[ -z "$username" ]]; then
                    read -rp "Enter username (or press Enter for guest): " username
                    if [[ -n "$username" ]]; then
                        echo "Enter password for $username:"
                        read -rs password
                        echo ""
                    fi
                fi

                setup_smb_mount "$share_name" "$username" "$password"
            else
                log_error "SMB setup failed"
                exit 1
            fi
            ;;
        2)
            log_info "Setting up NFS mount..."
            log_info "NFS (Network File System) exports are directory paths shared by the NAS"
            log_info "Examples: /volume1/media, /mnt/storage, /export/data"
            echo ""
            if test_nfs_exports; then
                echo ""
                echo "Available NFS exports are listed above."
                read -rp "Enter the export path to mount (e.g., /volume1/media): " export_path
                setup_nfs_mount "$export_path"
            else
                log_error "NFS setup failed - no exports available"
                log_info "Your NAS likely uses SMB/CIFS instead. Try option 1."
                exit 1
            fi
            ;;
        3)
            log_info "Testing both protocols..."

            smb_available=false
            nfs_available=false

            if test_smb_shares; then
                smb_available=true
                log_success "SMB/CIFS is available"
            fi

            echo ""

            if test_nfs_exports; then
                nfs_available=true
                log_success "NFS is available"
            fi

            echo ""

            if [[ "$smb_available" == true && "$nfs_available" == true ]]; then
                echo "Both SMB and NFS are available. NFS typically offers better performance for Linux systems."
                read -rp "Do you want to use NFS? (Y/n): " use_nfs

                if [[ "$use_nfs" =~ ^[Nn]$ ]]; then
                    read -rp "Enter the SMB share name to mount: " share_name
                    read -rp "Enter username (or press Enter for guest): " username

                    if [[ -n "$username" ]]; then
                        echo "Enter password for $username:"
                        read -rs password
                        echo ""
                    fi

                    setup_smb_mount "$share_name" "$username" "$password"
                else
                    echo "Available NFS exports are listed above."
                    read -rp "Enter the NFS export path to mount (e.g., /volume1/media): " export_path
                    setup_nfs_mount "$export_path"
                fi
            elif [[ "$smb_available" == true ]]; then
                log_info "Only SMB is available, proceeding with SMB setup..."
                read -rp "Enter the share name to mount: " share_name
                read -rp "Enter username (or press Enter for guest): " username

                if [[ -n "$username" ]]; then
                    echo "Enter password for $username:"
                    read -rs password
                    echo ""
                fi

                setup_smb_mount "$share_name" "$username" "$password"
            elif [[ "$nfs_available" == true ]]; then
                log_info "Only NFS is available, proceeding with NFS setup..."
                echo "Available NFS exports are listed above."
                read -rp "Enter the NFS export path to mount (e.g., /volume1/media): " export_path
                setup_nfs_mount "$export_path"
            else
                log_error "Neither SMB nor NFS is available on this NAS"
                exit 1
            fi
            ;;
        *)
            log_error "Invalid choice"
            exit 1
            ;;
    esac
}

# Test the mount
test_mount() {
    log_info "Testing the mount..."

    if sudo mount "$MOUNT_POINT"; then
        log_success "Mount successful!"

        # Test write access
        test_file="$MOUNT_POINT/.test_write_$(date +%s)"
        if touch "$test_file" 2>/dev/null; then
            log_success "Write access confirmed"
            rm -f "$test_file"
        else
            log_warning "Mount is read-only or write access denied"
        fi

        # Show mount info
        df -h "$MOUNT_POINT"

        echo ""
        read -rp "Do you want to unmount for now? (Y/n): " unmount_now
        if [[ ! "$unmount_now" =~ ^[Nn]$ ]]; then
            sudo umount "$MOUNT_POINT"
            log_info "Unmounted. Use 'sudo mount $MOUNT_POINT' to mount manually."
        fi
    else
        log_error "Mount failed!"
        exit 1
    fi
}

# Show usage instructions
show_usage_instructions() {
    log_success "=== NAS Mount Setup Complete ==="
    echo ""
    log_info "Your NAS is now configured for persistent mounting."
    echo ""
    echo "Usage instructions:"
    echo "• Manual mount: sudo mount $MOUNT_POINT"
    echo "• Manual unmount: sudo umount $MOUNT_POINT"
    echo "• The mount will be available after reboot via systemd"
    echo ""
    echo "Files and locations:"
    echo "• Mount point: $MOUNT_POINT"
    echo "• Fstab backup: $FSTAB_BACKUP"
    if [[ -f "$CREDENTIALS_FILE" ]]; then
        echo "• Credentials file: $CREDENTIALS_FILE (secure, 600 permissions)"
    fi
    echo "• Systemd unit: /etc/systemd/system/mnt-share-media.mount"
    echo ""
    log_info "To enable automatic mounting on boot:"
    echo "sudo systemctl start mnt-share-media.mount"
    echo ""
    log_warning "Remember to test the mount after a reboot to ensure it works correctly."
}

# Main function
main() {
    check_root
    check_prerequisites
    interactive_setup
    test_mount
    show_usage_instructions
}

# Run main function
main "$@"
