#!/bin/sh

# Check if dialog is present on the system (for graphical display).
# If not, install it.
if [ ! -x "/usr/pkg/bin/dialog" ]; then
    echo "The dialog program is not installed. Installation in progress..."
    pkgin -y in dialog
    pkgin -y in pico
    pkgin -y in curl
fi

checkInternetConnection () {
    # Start background internet connection check
    curl -m 3 http://example.com > /dev/null 2>&1 &
    pid=$!

    # Initialize the progress value
    progress=0

    # Loop to update the progress bar
    while [ $progress -le 100 ]; do
        # Check if curl is still running
        if ! kill -0 "$pid" 2>/dev/null; then
            # curl has finished
            break
        fi

        # Update the progress bar
        echo $progress
        progress=$((progress + 33)) # Increase the progress without $/
        sleep 1 # Wait 1 second
    done | dialog --gauge "Checking Internet connection..." 6 35 0

    # Check if the curl command was successful
    wait $pid
    exit_status=$?

    if [ $exit_status -ne 0 ]; then
        dialog --backtitle "Checking Internet connection" \
               --title "Connection error" \
               --msgbox "Internet access is not possible\nPlease check your connection" 6 35
        NetworkMenu
    fi
}

# checked

ItsOkInternet () {
    dialog --backtitle "Internet OK !" \
           --title " Result" \
           --msgbox "Internet OK !" 5 17

}

# checked

InstallSudo () {

    # Dialog window to get the username
    user=$(dialog --title "Adding sudo user" --inputbox "Please enter the username to be added to the sudo group" 8 60 2>&1 1>/dev/tty)

    # Check if the user exists using the 'getent passwd' command.
    countus=$(getent passwd "$user" | cut -d: -f1)
    case $countus in
        "$user")
            # The user exists, the script can continue.
            # Installation of sudo in the background
            if [ ! -x "/usr/pkg/bin/sudo" ]; then

                checkInternetConnection
                pkgin -y in sudo

            fi

            # Configuration of sudo after installation
            groupadd sudo

            # Check if the user is already in the sudo group
            verifgroupsudo=$(getent group | grep sudo | grep -c "$user" | tr -d ' ')
            if [ "$verifgroupsudo" -gt 0 ]; then
                dialog --msgbox "The user is already a member of the sudo group" 5 50
            else
                # Adding the user to the sudo group
                if ! usermod -G sudo "${user}"; then
                    dialog --msgbox "Adding the user to the sudo group failed" 7 44
                    return 1
                fi
            fi

            # Uncomment the line for the sudo group.
            sed -i "s/# %sudo/%sudo/" /usr/pkg/etc/sudoers

            # Check if the user has been added to sudo group
            verifgroupsudo=$(getent group | grep sudo | grep -c "$user" | tr -d ' ')
            if [ "$verifgroupsudo" -gt 0 ]; then
                dialog --msgbox "The user is now member of the sudo group" 5 45
            fi

            # Go back to Menu
            UsersRightsMenu
        ;;
        *)
            # The user does not exist, display a message.
            dialog --title "Erreur" --msgbox "This user does not exist" 5 28
            InstallSudo
        ;;
    esac

    UsersRightsMenu

}

# checked

DesktopBundleApps () {

    checkInternetConnection

    # Menu Title
    dialog --backtitle "Select programs" \
           --title "Installing applications" \
           --checklist "Select programs:" 30 70 20 \
           firefox "Firefox web browser" off \
           thunderbird "Thunderbird Mail Client" off \
           keepassxc "KeePassXC password manager" off \
           vlc "VLC multimedia player" off \
           handbrake "HandBrake video encoder" off \
           audacity "Audacity audio editor" off \
           gimp "GIMP image editor" off \
           ristretto "Ristretto image viewer" off \
           youtube-dl "YouTube video downloader" off \
           libreoffice "LibreOffice office suite" off \
           unoconv "Unoconv document converter" off \
           qpdfview "Qpdfview document viewer" off \
           filezilla "FileZilla FTP client" off \
           rclone "Rclone file transfer tool" off \
           rclone-browser "Rclone GUI interface (kapintainsky)" off \
           hexchat "HexChat IRC client" off \
           pidgin "Pidgin messaging client" off \
           psi "PSI messaging client" off \
           wireshark "Wireshark network protocol analyzer" off \
           nmap "Nmap network discovery tool" off \
           zenmap "Nmap graphical interface (Zenmap)" off \
           tor "Tor decentralized anonymous network" off \
           openvpn "OpenVPN Virtual Private Network setup" off \
           codeblocks "IDE for C/C++ development (Code::Blocks)" off \
           EVERYTHING "Install every packages of the list" off 2>/tmp/choices


    # Read the user choices from the temporary file.
    choices=$(sed 's/"//g' < /tmp/choices)

    # Count the number of selected programs.
    num_choices=$(echo "$choices" | wc -w)

    # Initialize the progress.
    progress=0
    (
    # Install the selected programs.
    for choice in $choices; do
        # Calculate and update the progress.
        progress=$((progress + 100 / num_choices))
        echo $progress

        if [ "$choice" = "EVERYTHING" ]; then
            pkgin -y in firefox
            echo 5
            pkgin -y in thunderbird
            echo 10
            pkgin -y in keepassxc
            echo 15
            pkgin -y in vlc
            echo 20
            pkgin -y in handbrake
            echo 25
            pkgin -y in audacity
            echo 30
            pkgin -y in gimp
            echo 35
            pkgin -y in ristretto
            echo 40
            pkgin -y in youtube-dl
            echo 45
            pkgin -y in libreoffice
            echo 50
            pkgin -y in unoconv
            echo 55
            pkgin -y in qpdfview
            echo 60
            pkgin -y in filezilla
            echo 65
            pkgin -y in rclone
            echo 70
            pkgin -y in hexchat
            echo 75
            pkgin -y in pidgin
            echo 80
            pkgin -y in psi
            echo 85
            pkgin -y in wireshark
            echo 90
            pkgin -y in nmap
            pkgin -y in zenmap
            echo 95
            pkgin -y in tor
            pkgin -y in openvpn
            pkgin -y in codeblocks
            echo 100

        else

            if [ "$choice" = "rclone-browser" ]; then

                pkgin install git cmake qt5-qtdeclarative rclone
                cd /usr/pkg
                git clone https://github.com/kapitainsky/RcloneBrowser.git
                sed -i 's/QString::SkipEmptyParts/Qt::SkipEmptyParts/' /usr/pkg/RcloneBrowser/src/main_window.cpp
                sed -i 's/player->start(stream, QProcess::ReadOnly);/QStringList arguments;\n  arguments << stream;\n  player->start("playerExecutable", arguments, QProcess::ReadOnly);/' /usr/pkg/RcloneBrowser/src/main_window.cpp
                cd /usr/pkg/RcloneBrowser
                mkdir build && cd build
                cmake .. -DCMAKE_PREFIX_PATH:PATH=/usr/pkg/qt5 -DCMAKE_INSTALL_RPATH=/usr/pkg/qt5/lib
                make
                make install

            else

                pkgin -y in "$choice"
            
            fi

        fi

    done
    ) | dialog --gauge "Installation in progress..." 6 32 0

    # Go back to InstallProgramsMenu
    InstallProgramsMenu
}

# checked

UsualTools () {

    checkInternetConnection

    #user=$(dialog --title "User" --inputbox "Please enter the username (not root!)" 8 50 2>&1 1>/dev/tty)

    # Menu Title
    dialog --backtitle "Utilities Selection" \
           --title "Installing Utilities" \
           --checklist "Select utilities:" 30 70 20 \
           xfce4-thunar "Thunar File Manager" off \
           xfce4-thunar-archive-plugin "Thunar Plugins" off \
           xfce4-thunar-media-tags-plugin "Thunar Plugins" off \
           xfce4-thunar-vcs-plugin "Thunar Plugins" off \
           wget "wget Download Tool" off \
           w3m "Text-based Web Browser" off \
           lynx "Text-based Web Browser" off \
           links "Text-based Web Browser" off \
           rsync "rsync Sync and Backup Tool" off \
           cesium "Text Editor" off \
           emacs "Text Editor" off \
           nano "Text Editor" off \
           fuse "Foreign Filesystem Management" off \
           fuse-ntfs "Foreign Filesystem Management" off \
           fuse-exfat "Foreign Filesystem Management" off \
           fuse-ext2 "Foreign Filesystem Management" off \
           fuse-httpfs "Foreign Filesystem Management" off \
           fuse-sshfs "Foreign Filesystem Management" off \
           ntfsprogs "NTFS Partition Management" off \
           dvd+rw-tools "CD/DVD/BD Burner" off \
           cdrtools "CD/DVD/BD Burner" off \
           wpa_gui "Wi-Fi Graphical Interface" off \
           cups "Printing Server" off \
           cups-filters "Printing Tools" off \
           zip "Compression Tools" off \
           unzip "Compression Tools" off \
           bzip2 "Compression Tools" off \
           bzip3 "Compression Tools" off \
           htop "Diagnostic Tools" off \
           hw-probe "Diagnostic Tools" off \
           dbus "D-Bus System Message Bus" off \
           tree "Tree Structure Display Tool" off \
           git "Github Tools" off \
           gh "Github Tools" off \
           xscreensaver "xscreensaver Screensaver" off \
           rdesktop "RDP Remote Desktop Tool" off \
           remmina "Remmina Remote Desktop Client" off \
           tigervnc "TigerVNC VNC client/server" off \
           megatools "Mega Management Tools" off \
           rp-pppoe "PPPoE connections" off \
           EVERYTHING "Install every packages of the list" off 2>/tmp/util_choices


    # Read the user choices from the temporary file.
    util_choices=$(sed 's/"//g' < /tmp/util_choices)

    # Count the number of selected utilities.
    num_choices=$(echo "$util_choices" | wc -w)

    # Initialize the progress.
    progress=0
    (
    # Install the selected utilities.
    for choice in $util_choices; do
        # Calculate and update the progress.
        progress=$((progress + 100 / num_choices))
        echo $progress

        if [ "$choice" = "EVERYTHING" ]; then

            pkgin -y in xfce4-thunar
            echo 2
            pkgin -y in xfce4-thunar-archive-plugin
            echo 4
            pkgin -y in xfce4-thunar-media-tags-plugin
            echo 6
            pkgin -y in xfce4-thunar-vcs-plugin
            echo 8
            pkgin -y in wget
            echo 10
            pkgin -y in w3m
            echo 12
            pkgin -y in lynx
            echo 14
            pkgin -y in links
            echo 16
            pkgin -y in rsync
            echo 18
            pkgin -y in cesium
            echo 20
            pkgin -y in emacs
            echo 22
            pkgin -y in nano
            echo 24
            pkgin -y in fuse
            echo 26
            pkgin -y in fuse-ntfs
            echo 28
            pkgin -y in fuse-exfat
            echo 30
            pkgin -y in fuse-ext2
            echo 32
            pkgin -y in fuse-httpfs
            echo 34
            pkgin -y in fuse-sshfs
            echo 36
            pkgin -y in ntfsprogs
            echo 38
            pkgin -y in dvd+rw-tools
            echo 40
            pkgin -y in cdrtools
            echo 42
            pkgin -y in wpa_gui
            echo 44
            pkgin -y in cups
            echo 46
            pkgin -y in cups-filters
            echo 48
            pkgin -y in zip
            echo 50
            pkgin -y in unzip
            echo 52
            pkgin -y in bzip2
            echo 54
            pkgin -y in bzip3
            echo 56
            pkgin -y in htop
            echo 58
            pkgin -y in hw-probe
            echo 60
            pkgin -y in dbus
            echo 62
            pkgin -y in tree
            echo 64
            pkgin -y in git
            echo 66
            pkgin -y in gh
            echo 68
            pkgin -y in xscreensaver
            echo 70
            pkgin -y in rdesktop
            echo 72
            pkgin -y in remmina
            echo 74
            pkgin -y in tigervnc
            echo 76
            pkgin -y in megatools
            echo 78
            pkgin -y in rp-pppoe
            mkdir /etc/ppp
            cp /usr/pkg/share/examples/rp-pppoe/pppoe.conf /etc/ppp/
            echo 80

            cp /usr/pkg/share/examples/rc.d/* /etc/rc.d/
            check=$(grep -o "cupsd=" < /etc/rc.conf | wc -l | tr -d ' ')
            if [ "$check" -eq 0 ]; then

                echo cupsd=YES
                service cupsd start

            else

                sed -i'' 's/cupsd=NO/cupsd=YES/' /etc/rc.conf
                sed -i'' 's/#cupsd=NO/cupsd=YES/' /etc/rc.conf
                sed -i'' 's/#cupsd=YES/cupsd=YES/' /etc/rc.conf

            fi

            check=$(grep -o "dbus=" < /etc/rc.conf | wc -l | tr -d ' ')
            if [ "$check" -eq 0 ]; then

                echo dbus=YES >> /etc/rc.conf
                service dbus start

            else

                sed -i'' 's/dbus=NO/dbus=YES/' /etc/rc.conf
                sed -i'' 's/#dbus=NO/dbus=YES/' /etc/rc.conf
                sed -i'' 's/#dbus=YES/dbus=YES/' /etc/rc.conf

            fi

            echo 100

            # Go back to InstallProgramsMenu
            InstallProgramsMenu

        else

            pkgin -y in "$choice"

        fi


        if [ "$choice" = "cups" ]; then

            check=$(grep -o "cupsd=" < /etc/rc.conf | wc -l | tr -d ' ')
            if [ "$check" -eq 0 ]; then

                echo cupsd=YES
                service cupsd start

            else

                sed -i'' 's/cupsd=NO/cupsd=YES/' /etc/rc.conf
                sed -i'' 's/#cupsd=NO/cupsd=YES/' /etc/rc.conf
                sed -i'' 's/#cupsd=YES/cupsd=YES/' /etc/rc.conf

            fi

        fi

        if [ "$choice" = "dbus" ]; then

            check=$(grep -o "dbus=" < /etc/rc.conf | wc -l | tr -d ' ')
            if [ "$check" -eq 0 ]; then

                echo dbus=YES
                service dbus start

            else

                sed -i'' 's/dbus=NO/dbus=YES/' /etc/rc.conf
                sed -i'' 's/#dbus=NO/dbus=YES/' /etc/rc.conf
                sed -i'' 's/#dbus=YES/dbus=YES/' /etc/rc.conf

            fi

        fi

        if [ "$choice" = "rp-pppoe" ]; then

            cp /usr/pkg/share/examples/rc.d/* /etc/rc.d/
            mkdir /etc/ppp
            cp /usr/pkg/share/examples/rp-pppoe/pppoe.conf /etc/ppp/
        fi

    done
    ) | dialog --gauge "Installation in progress..." 6 32 0

    # Go back to InstallProgramsMenu
    InstallProgramsMenu
}

BuildTools () {

    checkInternetConnection

    #user=$(dialog --title "User" --inputbox "Please enter the username (not root!)" 8 50 2>&1 1>/dev/tty)

    # Menu Title
    dialog --backtitle "Build Tools Selection" \
           --title "Installing Build Tools" \
           --checklist "Select Tools:" 30 70 20 \
           bmake "Build tool for NetBSD" off \
           gcc13 "GNU Compiler Collection" off \
           binutils "Binary utilities" off \
           m4 "Macro processor" off \
           cmake "Cross-platform make" off \
           autoconf "Automatic configure script builder" off \
           automake "Tool for generating Makefile.in files" off \
           libtool "Generic library support script" off \
           pkg-config "Package configuration tool" off \
           cvs "Concurrent Versions System" off \
           git "Distributed version control system" off \
           groff "GNU troff text-formatting system" off \
           gtexinfo "GNU documentation system" off \
           openssl "Toolkit for SSL/TLS" off \
           zlib "Compression library" off \
           gdb "GNU Debugger" off \
           EVERYTHING "Install every package from the list" off 2>/tmp/util_choices


    # Read the user choices from the temporary file.
    util_choices=$(sed 's/"//g' < /tmp/util_choices)

    # Count the number of selected utilities.
    num_choices=$(echo "$util_choices" | wc -w)

    # Initialize the progress.
    progress=0
    (
    # Install the selected utilities.
    for choice in $util_choices; do
        # Calculate and update the progress.
        progress=$((progress + 100 / num_choices))
        echo $progress

        if [ "$choice" = "EVERYTHING" ]; then

            pkgin -y in bmake
            echo 5
            pkgin -y in gcc13
            echo 10
            pkgin -y in binutils
            echo 15
            pkgin -y in m4
            echo 20
            pkgin -y in cmake
            echo 25
            pkgin -y in autoconf
            echo 30
            pkgin -y in automake
            echo 35
            pkgin -y in libtool
            echo 40
            pkgin -y in pkg-config
            echo 45
            pkgin -y in cvs
            echo 50
            pkgin -y in git
            echo 55
            pkgin -y in groff
            echo 60
            pkgin -y in gtexinfo
            echo 65
            pkgin -y in openssl
            echo 70
            pkgin -y in zlib
            echo 80
            pkgin -y in gdb
            echo 100

        else

            pkgin -y in "$choice"

        fi

    done
    ) | dialog --gauge "Installation in progress..." 6 32 0

    # Go back to InstallProgramsMenu
    InstallProgramsMenu
}


# checked

xfce4 () {

    dialog --yesno "This installer will set up XFCE4 and Slim automatically\nIt will not care about graphics, so if you don't already have a correct display with CTWM, you should not go on with XFCE4\n\nYou must have installed a complete version of NetBSD (with X) in order to get it working because this script will not install X\n\nAn already existing username will be asked in order to configure XFCE4 to start automatically after Slim authentication\n\nOff course, you must be connected to internet.\n\nOne last thing (and not the least): you absolutely must install the applications and utilities (menu 4 - Programs) BEFORE going on installing XFCE/Slim or you'll face a lot of conflicts after" 20 70
    goon_ornot=$?

    if [ $goon_ornot -eq 1 ]; then

        MainMenu

    fi

    checkInternetConnection

    user=$(dialog --title "User" --inputbox "Please enter the username (not root !)" 8 45 2>&1 1>/dev/tty)

    {
        # Install Slim
        pkgin -y in slim > /dev/null 2>&1
        echo 50
        pkgin -y in slim-themes > /dev/null 2>&1

        checkslim=$(grep -o "slim=YES" < /etc/rc.conf | sort | uniq | wc -l | tr -d ' ')
        if [ "$checkslim" -eq 0 ]; then
            echo slim=YES >> /etc/rc.conf
            sed -i "s/current_theme       original/current_theme       minimal/" /usr/pkg/etc/slim.conf
        fi

        sed -i "s/xdm=YES/xdm=NO/" /etc/rc.conf

        echo 100

    } | dialog --gauge "Installing Slim..." 6 23 0

    {
        # Install Xfce4
        pkgin -y in elementary-xfce-icon-theme > /dev/null 2>&1
        echo 2
        pkgin -y in libxfce4ui > /dev/null 2>&1
        echo 4
        pkgin -y in libxfce4util > /dev/null 2>&1
        echo 6
        pkgin -y in ristretto > /dev/null 2>&1
        echo 8
        pkgin -y in xfburn > /dev/null 2>&1
        echo 10
        pkgin -y in xfce4 > /dev/null 2>&1
        echo 12
        pkgin -y in xfce4-appfinder > /dev/null 2>&1
        echo 14
        pkgin -y in xfce4-battery-plugin > /dev/null 2>&1
        echo 16
        pkgin -y in xfce4-calculator-plugin > /dev/null 2>&1
        echo 18
        pkgin -y in xfce4-clipman-plugin > /dev/null 2>&1
        echo 20
        pkgin -y in xfce4-conf > /dev/null 2>&1
        echo 21
        pkgin -y in xfce4-cpugraph-plugin > /dev/null 2>&1
        echo 23
        pkgin -y in xfce4-dashboard > /dev/null 2>&1
        echo 24
        pkgin -y in xfce4-desktop > /dev/null 2>&1
        echo 26
        pkgin -y in xfce4-dev-tools > /dev/null 2>&1
        echo 27
        pkgin -y in xfce4-dict > /dev/null 2>&1
        echo 29
        pkgin -y in xfce4-diskperf-plugin > /dev/null 2>&1
        echo 30
        pkgin -y in xfce4-exo > /dev/null 2>&1
        echo 31
        pkgin -y in xfce4-extras > /dev/null 2>&1
        echo 33
        pkgin -y in xfce4-eyes-plugin > /dev/null 2>&1
        echo 34
        pkgin -y in xfce4-fsguard-plugin > /dev/null 2>&1
        echo 36
        pkgin -y in xfce4-garcon > /dev/null 2>&1
        echo 37
        pkgin -y in xfce4-genmon-plugin > /dev/null 2>&1
        echo 38
        pkgin -y in xfce4-icon-theme > /dev/null 2>&1
        echo 40
        pkgin -y in xfce4-indicator-plugin > /dev/null 2>&1
        echo 41
        pkgin -y in xfce4-mailwatch-plugin > /dev/null 2>&1
        echo 42
        pkgin -y in xfce4-mount-plugin > /dev/null 2>&1
        echo 50
        pkgin -y in xfce4-mousepad > /dev/null 2>&1
        echo 52
        pkgin -y in xfce4-mpc-plugin > /dev/null 2>&1
        echo 54
        pkgin -y in xfce4-netload-plugin > /dev/null 2>&1
        echo 56
        pkgin -y in xfce4-notes-plugin > /dev/null 2>&1
        echo 58
        pkgin -y in xfce4-notifyd > /dev/null 2>&1
        echo 60
        pkgin -y in xfce4-orage > /dev/null 2>&1
        echo 62
        pkgin -y in xfce4-panel > /dev/null 2>&1
        echo 64
        pkgin -y in xfce4-places-plugin > /dev/null 2>&1
        echo 66
        pkgin -y in xfce4-power-manager > /dev/null 2>&1
        echo 68
        pkgin -y in xfce4-screenshooter > /dev/null 2>&1
        echo 70
        pkgin -y in xfce4-session > /dev/null 2>&1
        echo 72
        pkgin -y in xfce4-settings > /dev/null 2>&1
        echo 73
        pkgin -y in xfce4-smartbookmark-plugin > /dev/null 2>&1
        echo 75
        pkgin -y in xfce4-systemload-plugin > /dev/null 2>&1
        echo 76
        pkgin -y in xfce4-taskmanager > /dev/null 2>&1
        echo 78
        pkgin -y in xfce4-terminal > /dev/null 2>&1
        echo 79
        pkgin -y in xfce4-thunar > /dev/null 2>&1
        echo 80
        pkgin -y in xfce4-thunar-archive-plugin > /dev/null 2>&1
        echo 81
        pkgin -y in xfce4-thunar-media-tags-plugin > /dev/null 2>&1
        echo 83
        pkgin -y in xfce4-thunar-vcs-plugin > /dev/null 2>&1
        echo 84
        pkgin -y in xfce4-time-out-plugin > /dev/null 2>&1
        echo 85
        pkgin -y in xfce4-timer-plugin > /dev/null 2>&1
        echo 87
        pkgin -y in xfce4-tumbler > /dev/null 2>&1
        echo 88
        pkgin -y in xfce4-verve-plugin > /dev/null 2>&1
        echo 89
        pkgin -y in xfce4-wavelan-plugin > /dev/null 2>&1
        echo 90
        pkgin -y in xfce4-weather-plugin > /dev/null 2>&1
        echo 91
        pkgin -y in xfce4-whiskermenu-plugin > /dev/null 2>&1
        echo 93
        pkgin -y in xfce4-wm > /dev/null 2>&1
        echo 94
        pkgin -y in xfce4-wm-themes > /dev/null 2>&1
        echo 96
        pkgin -y in xfce4-xkb-plugin > /dev/null 2>&1
        echo 97

        cp /usr/pkg/share/examples/rc.d/* /etc/rc.d/

        echo 100

        } | dialog --gauge "Installing Xfce..." 6 23 0

    dialog --yesno "Would you like to set XFCE to French?" 5 46
    xfce4_french=$?

    if [ $xfce4_french -eq 0 ]; then

            echo 'export LANG="fr_FR.UTF-8"' > /home/"$user"/.xsession
            echo 'export LC_CTYPE="fr_FR.UTF-8"' >> /home/"$user"/.xsession
            echo "startxfce4" >> /home/"$user"/.xsession

    else

        echo "startxfce4" > /home/"$user"/.xsession

    fi

    #echo 'export LANG="fr_FR.UTF-8"' > /home/$user/.xinitrc
    #echo 'export LC_CTYPE="fr_FR.UTF-8"' >> /home/$user/.xinitrc
    #echo "startxfce4" >> /home/$user/.xinitrc
    #echo "startx" >> /home/$user/.profile

    dialog --yesno "Would you like to restart now?" 5 34
    restart_now=$?

    if [ $restart_now -eq 0 ]; then

        reboot

    fi

    MainMenu
}

# checked

PareFeu () {

    echo "This script will allow you to quickly configure the NPF firewall

    It provides a file of standard rules that will be placed in /etc/npf.conf

    By default, the provided rules file will block all incoming traffic except for SSH (tcp/22) and allow all outgoing traffic in a stateful manner
    A blocklist table for fail2ban is also present, with a blocking rule associated in case you install fail2ban later

    However, the file contains a bunch of additional commented rules that will allow you to quickly adapt the configuration to your needs

    The next screen will display the provided rules file in a text editor
    You can make modifications as needed.
    Once you have made your modifications, exit the file and save it without changing its location

    At the end, you will be asked whether you confirm or not the application of the rules and the start of the firewall" > /tmp/ZRzepinzenr.tmp

    fold -s -w 67 /tmp/ZRzepinzenr.tmp > /tmp/ZR2zepinzenr.tmp

    dialog --title "NPF configuration" --textbox /tmp/ZR2zepinzenr.tmp 20 70

    rm /tmp/ZR2zepinzenr.tmp /tmp/ZRzepinzenr.tmp

    if [ -e "/etc/npf.conf" ]; then

        dialog --yesno "A rule file already exists in /etc/npf.conf.\nDo you want to edit the current file or delete it and start over with the default configuration?" 7 53
        check_file=$?

        if [ $check_file -eq 0 ]; then

            pico /etc/npf.conf

            dialog --yesno "Do you want to activate the NPF firewall?\n\nIf you are connected via SSH, the connection will be lost upon activation.\nHowever, if you haven't modified the rule allowing SSH traffic, you will be able to reconnect immediately." 11 60
            activate_npf=$?

            if [ $activate_npf -eq 0 ]; then

                checknpf=$(grep -o "npf=" < /etc/rc.conf | sort | uniq | wc -l | tr -d ' ')
                if [ "$checknpf" -eq 0 ]; then
                    echo npf=YES >> /etc/rc.conf
                else
                    sed -i'' 's/npf=NO/npf=YES/' /etc/rc.conf
                    sed -i'' 's/#npf=YES/npf=YES/' /etc/rc.conf
                    sed -i'' 's/#npf=NO/npf=YES/' /etc/rc.conf
                fi

                npfctl start
                npfctl reload /etc/npf.conf

            fi

            SecurityMenu

        fi

    fi
    # Creating the rules file:
    {
        echo "########################################################################"
        echo " "
        echo "# 1 - Provide information about your network interface(s):"
        echo " "
        echo "# WAN Interface :"
        echo "\$WAN_if = \"wm0\""
        echo "\$WAN_addrs = ifaddrs(wm0)"
        echo " "
        echo "# LAN Interface :"
        echo "# (Uncomment the following only if the server acts as a gateway)"
        echo "#\$LAN_if = \"wm1\""
        echo "#\$LAN_addrs = ifaddrs(wm1)"
        echo " "
        echo 'alg "icmp"'
        echo " "
        echo "########################################################################"
        echo " "
        echo "# 2 - Define the networks"
        echo " "
        echo "# The RFC protects the server from private networks in case it is directly facing the internet."
        echo "# (Uncomment only if the WAN IP is a public IP address)"
        echo "#\$RFC1918 = { 10.0.0.0/8, 172.16.0.0/14, 192.168.0.0/16 }"
        echo " "
        echo "# (Uncomment only if the server acts as a gateway)"
        echo "#\$LAN_net = { 10.10.10.0/24 }"
        echo " "
        echo "########################################################################"
        echo " "
        echo "# 3 - Create a NAT mapping for the LAN."
        echo " "
        echo "# (Uncomment only if the server acts as a gateway)"
        echo "#map inet4(\$WAN_if) dynamic \$LAN_net -> inet4(\$WAN_if)"
        echo " "
        echo "########################################################################"
        echo " "
        echo "# 4 - Create a procedure for logging connections:"
        echo " "
        echo 'procedure "log" {'
        echo '        # Send all events to a log (see npfd))'
        echo '        log: npflog0'
        echo '}'
        echo " "
        echo "########################################################################"
        echo " "
        echo "# 5 - Create tables"
        echo " "
        echo "# Create a table for fail2ban"
        echo "table <fail2ban> type ipset"
        echo " "
        echo "########################################################################"
        echo " "
        echo "# 6 - Rule group for the WAN interface:"
        echo " "
        echo "group \"WAN\" on \$WAN_if {"
        echo " "
        echo "        # Block IP from fail2ban table"
        echo "        block in final from <fail2ban> apply \"log\""
        echo " "
        echo "        # Allow all stateful outgoing traffic by selecting the protocol:"
        echo "        #pass stateful out final proto tcp all"
        echo "        #pass stateful out final proto udp all"
        echo "        #pass stateful out final proto icmp all"
        echo "        #pass stateful out final proto ipv6-icmp all"
        echo " "
        echo "        # Allow all stateful outgoing traffic (all protocols)."
        echo "        pass stateful out final all"
        echo " "
        echo "        # SSH: Allow SSH connections to the server"
        echo "        pass stateful in on \$WAN_if proto tcp to \$WAN_addrs port ssh"
        echo " "
        echo "        # Web Server: Allow HTTP and HTTPS connections to the server"
        echo "        #pass in final proto tcp from any to \$WAN_addrs port http"
        echo "        #pass in final proto tcp from any to \$WAN_addrs port https"
        echo " "
        echo "        # DHCP: Allow incoming responses from the DHCP server."
        echo "        #pass in family inet4 proto udp from any port bootps to any port bootpc"
        echo "        #pass in family inet6 proto udp from any to any port \"dhcpv6-client\""
        echo " "
        echo "        # Ping: Allow incoming ping requests"
        echo '        #pass in family inet4 proto icmp icmp-type echo all'
        echo '        #pass in final proto icmp icmp-type echo all'
        echo '        #pass in final proto icmp icmp-type timxceed all'
        echo '        #pass in final proto icmp icmp-type unreach all'
        echo '        #pass in final proto icmp icmp-type echoreply all'
        echo '        #pass in final proto icmp icmp-type sourcequench all'
        echo '        #pass in final proto icmp icmp-type paramprob all'
        echo '        #pass in final proto ipv6-icmp all'
        echo '        #pass family inet6 proto ipv6-icmp all'
        echo " "
        echo '        # Traceroute: Allow incoming traceroute.'
        echo '        #pass in proto udp to any port 33434-33600'
        echo " "
        echo '        # DNS: Allow incoming DNS requests'
        echo '        #pass stateful out final proto udp to any port domain'
        echo " "
        echo '        # mDNS: Allow local traffic'
        echo '        #pass in proto udp to any port mdns'
        echo " "
        echo '        # Block private networks:'
        echo "        #block in final from \$RFC1918 apply \"log\""
        echo "        #block out final to \$RFC1918 apply \"log\""
        echo " "
        echo '        # Forbidden IPs: (separate configuration)'
        echo '        # ruleset "blacklistd"'
        echo " "
        echo "        # IP Spoofing: Protect yourself (be careful not to cut off SSH access!)"
        echo '        #block in final from 127.0.0.1 apply "log"'
        echo " "
        echo '        # L2TP/IPSEC-NAT-T Tunnels.'
        echo "        #pass in final proto esp from any to inet4(\$WAN_if)"
        echo "        #pass out final proto esp from inet4(\$WAN_if) to any"
        echo "        #pass stateful in final from any to inet4(\$WAN_if) port \"ipsec-nat-t\""
        echo "        #pass stateful in final from any to inet4(\$WAN_if) port l2tp"
        echo " "
        echo '        # IGMP on 224.0.0.1.'
        echo '        #pass in final proto igmp all'
        echo '        #pass in final from any to 224.0.0.0/4'
        echo " "
        echo '        # VNC'
        echo "        #pass in final proto tcp from any to any port 5900"
        echo " "
        echo '}'
        echo " "
        echo "########################################################################"
        echo " "
        echo "# 7 - Rule group for the LAN interface:"
        echo " "
        echo "# (This group manages rules for the LAN interface when the server acts as a gateway)"
        echo " "
        echo "#group \"LAN\" on \$LAN_if {"
        echo " "
        echo "        # Allow stateful incoming and outgoing traffic"
        echo '        #pass stateful out final all'
        echo '        #pass stateful in final all'
        echo " "
        echo "        # Allow connections from the LAN network:"
        echo "        #pass in final from \$LAN_net"
        echo " "
        echo "        # Allow all traffic"
        echo "        #pass in final all"
        echo "        #pass out final all"
        echo " "
        echo '#}'
        echo " "
        echo "########################################################################"
        echo " "
        echo "# 8 - Default rule group:"
        echo " "
        echo 'group default {'
        echo " "
        echo '       # Loopback : Allow traffic'
        echo "       pass final on lo0 all"
        echo " "
        echo '        # Close the firewall'
        echo '       block all apply "log"'
        echo " "
        echo '}'
        echo "########################################################################"
    } > /etc/npf.conf

    pico /etc/npf.conf

    dialog --yesno "Do you want to activate the NPF firewall?\n\nIf you are connected via SSH, the connection will be lost upon activation.\nHowever, if you haven't modified the rule allowing SSH traffic, you will be able to reconnect immediately." 10 60
    activate_npf=$?

    if [ $activate_npf -eq 0 ]; then

        checknpf=$(grep -o "npf=" < /etc/rc.conf | sort | uniq | wc -l | tr -d ' ')
        if [ "$checknpf" -eq 0 ]; then

            # Launch NPF at startup:
            echo npf=YES >> /etc/rc.conf
        else
            # Launch NPF at startup:
            sed -i'' 's/npf=NO/npf=YES/' /etc/rc.conf
            sed -i'' 's/#npf=YES/npf=YES/' /etc/rc.conf
            sed -i'' 's/#npf=NO/npf=YES/' /etc/rc.conf
        fi

        # Start NPF, load the rules
        npfctl start
        npfctl reload /etc/npf.conf

    fi

    PareFeuMenu
}

# checked

ShowRulesNPF () {

    if [ ! -e "/etc/npf.conf" ]; then
        dialog --msgbox "The firewall is not yet configured." 5 38
        PareFeuMenu
    fi

    npfctl show > /tmp/Gzebpnief.tmp

    dialog --textbox /tmp/Gzebpnief.tmp 0 0

    rm /tmp/Gzebpnief.tmp

    PareFeuMenu
}

# checked

InstallFail2ban () {

    {
        # check if fail2ban is already installed
        if [ ! -e /usr/pkg/bin/fail2ban-server ]; then

            checkInternetConnection

            echo 10

            pkgin -y in fail2ban > /dev/null 2>&1

            echo 50

            cp /usr/pkg/share/examples/rc.d/fail2ban /etc/rc.d/

            # check for fail2ban in /etc/rc.conf
            check=$(grep -o 'fail2ban=' < /etc/rc.conf | sort | uniq | tr -d ' ')
            if [ "$check" -eq 0 ]; then

                echo fail2ban=YES >>  /etc/rc.conf

            else

                sed -i'' "s/fail2ban=NO/fail2ban=YES/" /etc/rc.conf
                sed -i'' "s/#fail2ban=YES/fail2ban=YES/" /etc/rc.conf
                sed -i'' "s/#fail2ban=NO/fail2ban=YES/" /etc/rc.conf

            fi


            # check for other things :
            mkdir /usr/pkg/etc/fail2ban/filter.d/ignorecommands
            cp /usr/pkg/share/examples/fail2ban/filter.d/ignorecommands/apache-fakegooglebot /usr/pkg/etc/fail2ban/filter.d/ignorecommands/
            chmod 0644 /usr/pkg/etc/fail2ban/filter.d/ignorecommands/apache-fakegooglebot

        fi

        echo 100

    } | dialog --gauge "Check for fail2ban..." 6 25 0


    # checking for NPF correct configuration for fail2ban :
    if [ ! -e /etc/npf.conf ]; then

        dialog --yesno "To allow fail2ban to function properly, the NPF firewall must be configured and started beforehand\n\nDo you want to configure NPF now?" 9 70
        npfnow_ornot=$?
        if [ $npfnow_ornot -eq 0 ]; then

            PareFeu

        fi

    fi


    #Check for previous configuration
    if [ -e /usr/pkg/etc/fail2ban/jail.local ]; then


        dialog --yesno "A previous configuration of Fail2ban has been found\n\nWould you like to edit it (Yes) or start from a new configuration (No)" 8 70
        new_ornot=$?

        if [ $new_ornot -eq 1 ]; then

            # Standard fail2ban.local :
            {
                echo '[INCLUDES]'
                echo 'before = paths-pkgsrc.conf'

                echo ''

                echo '[DEFAULT]'
                echo 'ignoreip = 127.0.0.1/8'
                echo 'bantime = 10m'
                echo 'findtime = 10m'
                echo 'maxretry = 5'
                echo 'maxmatches = %(maxretry)s'
                echo 'backend = auto'
                echo 'usedns = warn'
                echo 'logencoding = auto'
                echo 'enabled = false'
                echo 'mode = normal'
                echo 'filter = %(__name__)s[mode=%(mode)s]'

                echo ''

                echo 'destemail = root@localhost'
                echo 'sender = root@<fq-hostname>'
                echo 'mta = sendmail'
                echo 'protocol = tcp'
                echo 'chain = <known/chain>'
                echo 'port = 0:65535'
                echo 'fail2ban_agent = Fail2Ban/%(fail2ban_version)s'

                echo ''

                echo 'banaction = npf'

                echo ''

                echo '[sshd]'
                echo '# To use more aggressive sshd modes set filter parameter "mode" in jail.local:'
                echo '# normal (default), ddos, extra or aggressive (combines all).'
                echo '# See "tests/files/logs/sshd" or "filter.d/sshd.conf" for usage example and details.'
                echo '#mode   = normal'
                echo 'enabled = true'
                echo 'port    = ssh'
                echo 'logpath = /var/log/authlog'
                echo 'backend = %(sshd_backend)s'

                echo ''

                echo '[dropbear]'
                echo 'port     = ssh'
                echo 'logpath  = %(dropbear_log)s'
                echo 'backend  = %(dropbear_backend)s'

                echo ''

                echo '[selinux-ssh]'
                echo 'port     = ssh'
                echo 'logpath  = %(auditd_log)s'

                echo ''

                echo '#'
                echo '# HTTP servers'
                echo '#'

                echo '[apache-auth]'
                echo 'port     = http,https'
                echo 'logpath  = %(apache_error_log)s'

                echo ''

                echo '[apache-badbots]'
                echo '# Ban hosts which agent identifies spammer robots crawling the web'
                echo '# for email addresses. The mail outputs are buffered.'
                echo 'port     = http,https'
                echo 'logpath  = %(apache_access_log)s'
                echo 'bantime  = 48h'
                echo 'maxretry = 1'

                echo ''

                echo '[apache-noscript]'
                echo 'port     = http,https'
                echo 'logpath  = %(apache_error_log)s'

                echo ''

                echo '[apache-overflows]'
                echo 'port     = http,https'
                echo 'logpath  = %(apache_error_log)s'
                echo 'maxretry = 2'

                echo ''

                echo '[apache-nohome]'
                echo 'port     = http,https'
                echo 'logpath  = %(apache_error_log)s'
                echo 'maxretry = 2'

                echo ''

                echo '[apache-botsearch]'
                echo 'port     = http,https'
                echo 'logpath  = %(apache_error_log)s'
                echo 'maxretry = 2'

                echo ''

                echo '[apache-fakegooglebot]'
                echo 'port     = http,https'
                echo 'logpath  = %(apache_access_log)s'
                echo 'maxretry = 1'
                echo 'ignorecommand = %(fail2ban_confpath)s/filter.d/ignorecommands/apache-fakegooglebot <ip>'

                echo ''

                echo '[apache-modsecurity]'
                echo 'port     = http,https'
                echo 'logpath  = %(apache_error_log)s'
                echo 'maxretry = 2'

                echo ''

                echo '[apache-shellshock]'
                echo 'port    = http,https'
                echo 'logpath = %(apache_error_log)s'
                echo 'maxretry = 1'

                echo ''

                echo '[openhab-auth]'
                echo 'filter = openhab'
                echo 'banaction = %(banaction_allports)s'
                echo 'logpath = /opt/openhab/logs/request.log'

                echo ''

                echo '# To use more aggressive http-auth modes set filter parameter "mode" in jail.local:'
                echo '# normal (default), aggressive (combines all), auth or fallback'
                echo '[nginx-http-auth]'
                echo '# mode = normal'
                echo 'port    = http,https'
                echo 'logpath = %(nginx_error_log)s'

                echo ''

                echo "# To use 'nginx-limit-req' jail you should have \`ngx_http_limit_req_module\`"
                echo "# and define \`limit_req\` and \`limit_req_zone\` as described in nginx documentation"
                echo '# http://nginx.org/en/docs/http/ngx_http_limit_req_module.html'
                echo '# or for example see in '\''config/filter.d/nginx-limit-req.conf'\'''
                echo '[nginx-limit-req]'
                echo 'port    = http,https'
                echo 'logpath = %(nginx_error_log)s'

                echo ''

                echo '[nginx-botsearch]'
                echo 'port     = http,https'
                echo 'logpath  = %(nginx_error_log)s'

                echo ''

                echo '[nginx-bad-request]'
                echo 'port    = http,https'
                echo 'logpath = %(nginx_access_log)s'

                echo ''

                echo "# Ban attackers that try to use PHP's URL-fopen() functionality"
                echo '# through GET/POST variables. - Experimental, with more than a year'
                echo '# of usage in production environments.'

                echo ''

                echo '[php-url-fopen]'
                echo 'port    = http,https'
                echo 'logpath = %(nginx_access_log)s'
                echo '          %(apache_access_log)s'

                echo ''

                echo '[suhosin]'
                echo 'port    = http,https'
                echo 'logpath = %(suhosin_log)s'

                echo ''

                echo '[lighttpd-auth]'
                echo '# Same as above for Apache'\''s mod_auth'
                echo '# It catches wrong authentifications'
                echo 'port    = http,https'
                echo 'logpath = %(lighttpd_error_log)s'

                echo ''

                echo '#'
                echo '# Webmail and groupware servers'
                echo '#'

                echo '[roundcube-auth]'
                echo 'port     = http,https'
                echo 'logpath  = %(roundcube_errors_log)s'
                echo '# Use following line in your jail.local if roundcube logs to journal.'
                echo '#backend = %(syslog_backend)s'

                echo ''

                echo '[openwebmail]'
                echo 'port     = http,https'
                echo 'logpath  = /var/log/openwebmail.log'

                echo ''

                echo '[horde]'
                echo 'port     = http,https'
                echo 'logpath  = /var/log/horde/horde.log'

                echo ''

                echo '[groupoffice]'
                echo 'port     = http,https'
                echo 'logpath  = /home/groupoffice/log/info.log'

                echo ''

                echo '[sogo-auth]'
                echo '# Monitor SOGo groupware server'
                echo '# without proxy this would be:'
                echo '# port    = 20000'
                echo 'port     = http,https'
                echo 'logpath  = /var/log/sogo/sogo.log'

                echo ''

                echo '[tine20]'
                echo 'logpath  = /var/log/tine20/tine20.log'
                echo 'port     = http,https'

                echo ''

                echo '#'
                echo '# Web Applications'
                echo '#'

                echo '[drupal-auth]'
                echo 'port     = http,https'
                echo 'logpath  = %(syslog_daemon)s'
                echo 'backend  = %(syslog_backend)s'

                echo ''

                echo '[guacamole]'
                echo 'port     = http,https'
                echo 'logpath  = /var/log/tomcat*/catalina.out'
                echo '#logpath  = /var/log/guacamole.log'

                echo ''

                echo '[monit]'
                echo '#Ban clients brute-forcing the monit gui login'
                echo 'port = 2812'
                echo 'logpath  = /var/log/monit'
                echo '           /var/log/monit.log'

                echo ''

                echo '[webmin-auth]'
                echo 'port    = 10000'
                echo 'logpath = %(syslog_authpriv)s'
                echo 'backend = %(syslog_backend)s'

                echo ''

                echo '[froxlor-auth]'
                echo 'port    = http,https'
                echo 'logpath  = %(syslog_authpriv)s'
                echo 'backend  = %(syslog_backend)s'

                echo ''

                echo '#'
                echo '# HTTP Proxy servers'
                echo '#'

                echo '[squid]'
                echo 'port     =  80,443,3128,8080'
                echo 'logpath = /var/log/squid/access.log'

                echo ''

                echo '[3proxy]'
                echo 'port    = 3128'
                echo 'logpath = /var/log/3proxy.log'

                echo ''

                echo '#'
                echo '# FTP servers'
                echo '#'

                echo '[proftpd]'
                echo 'port     = ftp,ftp-data,ftps,ftps-data'
                echo 'logpath  = %(proftpd_log)s'
                echo 'backend  = %(proftpd_backend)s'

                echo ''

                echo '[pure-ftpd]'
                echo 'port     = ftp,ftp-data,ftps,ftps-data'
                echo 'logpath  = %(pureftpd_log)s'
                echo 'backend  = %(pureftpd_backend)s'

                echo ''

                echo '[gssftpd]'
                echo 'port     = ftp,ftp-data,ftps,ftps-data'
                echo 'logpath  = %(syslog_daemon)s'
                echo 'backend  = %(syslog_backend)s'

                echo ''

                echo '[wuftpd]'
                echo 'port     = ftp,ftp-data,ftps,ftps-data'
                echo 'logpath  = %(wuftpd_log)s'
                echo 'backend  = %(wuftpd_backend)s'

                echo ''

                echo '[vsftpd]'
                echo '# or overwrite it in jails.local to be'
                echo '# logpath = %(syslog_authpriv)s'
                echo '# if you want to rely on PAM failed login attempts'
                echo "# vsftpd's failregex should match both of those formats"
                echo 'port     = ftp,ftp-data,ftps,ftps-data'
                echo 'logpath  = %(vsftpd_log)s'

                echo ''

                echo '#'
                echo '# Mail servers'
                echo '#'

                echo '# ASSP SMTP Proxy Jail'
                echo '[assp]'
                echo 'port     = smtp,465,submission'
                echo 'logpath  = /root/path/to/assp/logs/maillog.txt'

                echo ''

                echo '[courier-smtp]'
                echo 'port     = smtp,465,submission'
                echo 'logpath  = %(syslog_mail)s'
                echo 'backend  = %(syslog_backend)s'

                echo ''

                echo '[postfix]'
                echo '# To use another modes set filter parameter "mode" in jail.local:'
                echo 'mode    = more'
                echo 'port    = smtp,465,submission'
                echo 'logpath = %(postfix_log)s'
                echo 'backend = %(postfix_backend)s'

                echo ''

                echo '[postfix-rbl]'
                echo 'filter   = postfix[mode=rbl]'
                echo 'port     = smtp,465,submission'
                echo 'logpath  = %(postfix_log)s'
                echo 'backend  = %(postfix_backend)s'
                echo 'maxretry = 1'

                echo ''

                echo '[sendmail-auth]'
                echo 'port    = submission,465,smtp'
                echo 'logpath = %(syslog_mail)s'
                echo 'backend = %(syslog_backend)s'

                echo ''

                echo '[sendmail-reject]'
                echo '# To use more aggressive modes set filter parameter "mode" in jail.local:'
                echo '# normal (default), extra or aggressive'
                echo '# See "tests/files/logs/sendmail-reject" or "filter.d/sendmail-reject.conf" for usage example and details.'
                echo '#mode    = normal'
                echo 'port     = smtp,465,submission'
                echo 'logpath  = %(syslog_mail)s'
                echo 'backend  = %(syslog_backend)s'

                echo ''

                echo '[qmail-rbl]'
                echo 'filter  = qmail'
                echo 'port    = smtp,465,submission'
                echo 'logpath = /service/qmail/log/main/current'

                echo ''

                echo '# dovecot defaults to logging to the mail syslog facility'
                echo '# but can be set by syslog_facility in the dovecot configuration.'
                echo '[dovecot]'
                echo 'port    = pop3,pop3s,imap,imaps,submission,465,sieve'
                echo 'logpath = %(dovecot_log)s'
                echo 'backend = %(dovecot_backend)s'

                echo ''

                echo '[sieve]'
                echo 'port   = smtp,465,submission'
                echo 'logpath = %(dovecot_log)s'
                echo 'backend = %(dovecot_backend)s'

                echo ''

                echo '[solid-pop3d]'
                echo 'port    = pop3,pop3s'
                echo 'logpath = %(solidpop3d_log)s'

                echo ''

                echo '[exim]'
                echo '# see filter.d/exim.conf for further modes supported from filter:'
                echo '#mode = normal'
                echo 'port   = smtp,465,submission'
                echo 'logpath = %(exim_main_log)s'

                echo ''

                echo '[exim-spam]'
                echo 'port   = smtp,465,submission'
                echo 'logpath = %(exim_main_log)s'

                echo ''

                echo '[kerio]'
                echo 'port    = imap,smtp,imaps,465'
                echo 'logpath = /opt/kerio/mailserver/store/logs/security.log'

                echo ''

                echo '#'
                echo '# Mail servers authenticators: might be used for smtp,ftp,imap servers, so'
                echo '# all relevant ports get banned'
                echo '#'

                echo ''

                echo '[courier-auth]'
                echo 'port     = smtp,465,submission,imap,imaps,pop3,pop3s'
                echo 'logpath  = %(syslog_mail)s'
                echo 'backend  = %(syslog_backend)s'

                echo ''

                echo '[postfix-sasl]'
                echo 'filter   = postfix[mode=auth]'
                echo 'port     = smtp,465,submission,imap,imaps,pop3,pop3s'
                echo '# You might consider monitoring /var/log/mail.warn instead if you are'
                echo '# running postfix since it would provide the same log lines at the'
                echo '# "warn" level but overall at the smaller filesize.'
                echo 'logpath  = %(postfix_log)s'
                echo 'backend  = %(postfix_backend)s'

                echo ''

                echo '[perdition]'
                echo 'port   = imap,imaps,pop3,pop3s'
                echo 'logpath = %(syslog_mail)s'
                echo 'backend = %(syslog_backend)s'

                echo ''

                echo '[squirrelmail]'
                echo 'port = smtp,465,submission,imap,imap2,imaps,pop3,pop3s,http,https,socks'
                echo 'logpath = /var/db/squirrelmail/prefs/squirrelmail_access_log'

                echo ''

                echo '[cyrus-imap]'
                echo 'port   = imap,imaps'
                echo 'logpath = %(syslog_mail)s'
                echo 'backend = %(syslog_backend)s'

                echo ''

                echo '[uwimap-auth]'
                echo 'port   = imap,imaps'
                echo 'logpath = %(syslog_mail)s'
                echo 'backend = %(syslog_backend)s'

                echo ''

                echo '#'
                echo '#'
                echo '# DNS servers'
                echo '#'
                echo ''

                echo '#'
                echo '#'
                echo '# !!! WARNING !!!'
                echo '#   Since UDP is connection-less protocol, spoofing of IP and imitation'
                echo '#   of illegal actions is way too simple.  Thus enabling of this filter'
                echo '#   might provide an easy way for implementing a DoS against a chosen'
                echo '#   victim. See'
                echo '#    http://nion.modprobe.de/blog/archives/690-fail2ban-+-dns-fail.html'
                echo '#   Please DO NOT USE this jail unless you know what you are doing.'
                echo '#'
                echo '# IMPORTANT: see filter.d/named-refused for instructions to enable logging'
                echo '# This jail blocks UDP traffic for DNS requests.'
                echo '# [named-refused-udp]'
                echo '#'
                echo '# filter   = named-refused'
                echo '# port     = domain,953'
                echo '# protocol = udp'
                echo '# logpath  = /var/log/named/security.log'

                echo '#'
                echo '#'

                echo '# IMPORTANT: see filter.d/named-refused for instructions to enable logging'
                echo '# This jail blocks TCP traffic for DNS requests.'

                echo ''
                echo ''

                echo '[named-refused]'
                echo 'port     = domain,953'
                echo 'logpath  = /var/log/named/security.log'

                echo ''
                echo ''

                echo '[nsd]'
                echo 'port     = 53'
                echo 'action_  = %(default/action_)s[name=%(__name__)s-tcp, protocol="tcp"]'
                echo '           %(default/action_)s[name=%(__name__)s-udp, protocol="udp"]'
                echo 'logpath = /var/log/nsd.log'

                echo ''

                echo '#'
                echo '# Miscellaneous'
                echo '#'

                echo ''

                echo '[asterisk]'
                echo 'port     = 5060,5061'
                echo 'action_  = %(default/action_)s[name=%(__name__)s-tcp, protocol="tcp"]'
                echo '           %(default/action_)s[name=%(__name__)s-udp, protocol="udp"]'
                echo 'logpath  = /var/log/asterisk/messages'
                echo 'maxretry = 10'

                echo ''

                echo '[freeswitch]'
                echo 'port     = 5060,5061'
                echo 'action_  = %(default/action_)s[name=%(__name__)s-tcp, protocol="tcp"]'
                echo '           %(default/action_)s[name=%(__name__)s-udp, protocol="udp"]'
                echo 'logpath  = /var/log/freeswitch.log'
                echo 'maxretry = 10'

                echo ''

                echo '# enable adminlog; it will log to a file inside znc'\''s directory by default.'
                echo '[znc-adminlog]'
                echo 'port     = 6667'
                echo 'logpath  = /var/db/znc/moddata/adminlog/znc.log'

                echo ''

                echo '# To log wrong MySQL access attempts add to /usr/pkg/etc/my.cnf in [mysqld] or'
                echo '# equivalent section:'
                echo '# log-warnings = 2'
                echo '#'
                echo '# for syslog (daemon facility)'
                echo '# [mysqld_safe]'
                echo '# syslog'
                echo '#'
                echo '# for own logfile'
                echo '# [mysqld]'
                echo '# log-error=/var/log/mysqld.log'
                echo '[mysqld-auth]'
                echo 'port     = 3306'
                echo 'logpath  = %(mysql_log)s'
                echo 'backend  = %(mysql_backend)s'

                echo ''

                echo '[mssql-auth]'
                echo '# Default configuration for Microsoft SQL Server for Linux'
                echo '# See the '\''mssql-conf'\'' manpage how to change logpath or port'
                echo 'logpath = /var/opt/mssql/log/errorlog'
                echo 'port = 1433'
                echo 'filter = mssql-auth'

                echo ''

                echo '# Log wrong MongoDB auth (for details see filter '\''filter.d/mongodb-auth.conf'\'')'
                echo '[mongodb-auth]'
                echo '# change port when running with "--shardsvr" or "--configsvr" runtime operation'
                echo 'port     = 27017'
                echo 'logpath  = /var/log/mongodb/mongodb.log'
                echo ''
                echo '# Jail for more extended banning of persistent abusers'
                echo '# !!! WARNINGS !!!'
                echo '# 1. Make sure that your loglevel specified in fail2ban.conf/.local'
                echo '#    is not at DEBUG level -- which might then cause fail2ban to fall into'
                echo '#    an infinite loop constantly feeding itself with non-informative lines'
                echo '# 2. Increase dbpurgeage defined in fail2ban.conf to e.g. 648000 (7.5 days)'
                echo '#    to maintain entries for failed logins for sufficient amount of time'
                echo '[recidive]'
                echo ''
                echo 'logpath  = /var/log/fail2ban.log'
                echo 'banaction = %(banaction_allports)s'
                echo 'bantime  = 1w'
                echo 'findtime = 1d'

                echo ''

                echo '# Generic filter for PAM. Has to be used with action which bans all'
                echo '# ports such as iptables-allports, shorewall'

                echo ''

                echo '[pam-generic]'
                echo '# pam-generic filter can be customized to monitor specific subset of '\''tty'\''s'
                echo 'banaction = %(banaction_allports)s'
                echo 'logpath  = %(syslog_authpriv)s'
                echo 'backend  = %(syslog_backend)s'

                echo ''

                echo '[xinetd-fail]'
                echo 'banaction = iptables-multiport-log'
                echo 'logpath   = %(syslog_daemon)s'
                echo 'backend   = %(syslog_backend)s'
                echo 'maxretry  = 2'

                echo ''

                echo '# stunnel - need to set port for this'
                echo '[stunnel]'
                echo 'logpath = /var/log/stunnel4/stunnel.log'

                echo ''

                echo '[ejabberd-auth]'
                echo 'port    = 5222'
                echo 'logpath = /var/log/ejabberd/ejabberd.log'

                echo ''

                echo '[counter-strike]'
                echo 'logpath = /opt/cstrike/logs/L[0-9]*.log'
                echo 'tcpport = 27030,27031,27032,27033,27034,27035,27036,27037,27038,27039'
                echo 'udpport = 1200,27000,27001,27002,27003,27004,27005,27006,27007,27008,27009,27010,27011,27012,27013,27014,27015'
                echo 'action_  = %(default/action_)s[name=%(__name__)s-tcp, port="%(tcpport)s", protocol="tcp"]'
                echo '           %(default/action_)s[name=%(__name__)s-udp, port="%(udpport)s", protocol="udp"]'

                echo ''

                echo '[softethervpn]'
                echo 'port     = 500,4500'
                echo 'protocol = udp'
                echo 'logpath  = /usr/local/vpnserver/security_log/*/sec.log'

                echo ''

                echo '[gitlab]'
                echo 'port    = http,https'
                echo 'logpath = /var/log/gitlab/gitlab-rails/application.log'

                echo ''

                echo '[grafana]'
                echo 'port    = http,https'
                echo 'logpath = /var/log/grafana/grafana.log'

                echo ''

                echo '[bitwarden]'
                echo 'port    = http,https'
                echo 'logpath = /home/*/bwdata/logs/identity/Identity/log.txt'

                echo ''

                echo '[centreon]'
                echo 'port    = http,https'
                echo 'logpath = /var/log/centreon/login.log'

                echo ''

                echo '# consider low maxretry and a long bantime'
                echo '# nobody except your own Nagios server should ever probe nrpe'
                echo '[nagios]'
                echo 'logpath  = %(syslog_daemon)s     ; nrpe.cfg may define a different log_facility'
                echo 'backend  = %(syslog_backend)s'
                echo 'maxretry = 1'

                echo ''

                echo '[oracleims]'
                echo '# see "oracleims" filter file for configuration requirement for Oracle IMS v6 and above'
                echo 'logpath = /opt/sun/comms/messaging64/log/mail.log_current'
                echo 'banaction = %(banaction_allports)s'

                echo ''

                echo '[directadmin]'
                echo 'logpath = /var/log/directadmin/login.log'
                echo 'port = 2222'

                echo ''

                echo '[portsentry]'
                echo 'logpath  = /var/db/portsentry/portsentry.history'
                echo 'maxretry = 1'

                echo ''

                echo '[pass2allow-ftp]'
                echo '# this pass2allow example allows FTP traffic after successful HTTP authentication'
                echo 'port         = ftp,ftp-data,ftps,ftps-data'
                echo '# knocking_url variable must be overridden to some secret value in jail.local'
                echo 'knocking_url = /knocking/'
                echo 'filter       = apache-pass[knocking_url="%(knocking_url)s"]'
                echo '# access log of the website with HTTP auth'
                echo 'logpath      = %(apache_access_log)s'
                echo 'blocktype    = RETURN'
                echo 'returntype   = DROP'
                echo 'action       = %(action_)s[blocktype=%(blocktype)s, returntype=%(returntype)s,'
                echo '                        actionstart_on_demand=false, actionrepair_on_unban=true]'
                echo 'bantime      = 1h'
                echo 'maxretry     = 1'
                echo 'findtime     = 1'

                echo ''

                echo '[murmur]'
                echo '# AKA mumble-server'
                echo 'port     = 64738'
                echo 'action_  = %(default/action_)s[name=%(__name__)s-tcp, protocol="tcp"]'
                echo '           %(default/action_)s[name=%(__name__)s-udp, protocol="udp"]'
                echo 'logpath  = /var/log/mumble-server/mumble-server.log'

                echo ''

                echo '[screensharingd]'
                echo '# For Mac OS Screen Sharing Service (VNC)'
                echo 'logpath  = /var/log/system.log'
                echo 'logencoding = utf-8'

                echo ''

                echo '[haproxy-http-auth]'
                echo "# HAProxy by default doesn't log to file you'll need to set it up to forward"
                echo '# logs to a syslog server which would then write them to disk.'
                echo '# See "haproxy-http-auth" filter for a brief cautionary note when setting'
                echo '# maxretry and findtime.'
                echo 'logpath  = /var/log/haproxy.log'

                echo ''

                echo '[slapd]'
                echo 'port    = ldap,ldaps'
                echo 'logpath = /var/log/slapd.log'
                echo ''
                echo '[domino-smtp]'
                echo 'port    = smtp,ssmtp'
                echo 'logpath = /home/domino01/data/IBM_TECHNICAL_SUPPORT/console.log'

                echo ''

                echo '[phpmyadmin-syslog]'
                echo 'port    = http,https'
                echo 'logpath = %(syslog_authpriv)s'
                echo 'backend = %(syslog_backend)s'

                echo ''

                echo '[zoneminder]'
                echo '# Zoneminder HTTP/HTTPS web interface auth'
                echo '# Logs auth failures to apache2 error log'
                echo 'port    = http,https'
                echo 'logpath = %(apache_error_log)s'

                echo ''

                echo '[traefik-auth]'
                echo "# to use 'traefik-auth' filter you have to configure your Traefik instance,"
                echo "# see \`filter.d/traefik-auth.conf\` for details and service example."
                echo 'port    = http,https'
                echo 'logpath = /var/log/traefik/access.log'

                echo ''

                echo '[scanlogd]'
                echo 'logpath = %(syslog_local0)s'
                echo 'banaction = %(banaction_allports)s'

                echo ''

                echo '[monitorix]'
                echo 'port	= 8080'
                echo 'logpath = /var/log/monitorix-httpd'
            } > /usr/pkg/etc/fail2ban/jail.local


            pico /usr/pkg/etc/fail2ban/jail.local

        else

            pico /usr/pkg/etc/fail2ban/jail.local

            dialog --yesno "Do you want to (re)start fail2ban?" 5 39
            restart_ornot=$?
            if [ $restart_ornot -eq 0 ]; then

                service fail2ban restart > /dev/null 2>&1

                Fail2banMenu

            fi

        fi

        dialog --yesno "Do you want to (re)start fail2ban?" 5 39
        restart_ornot=$?
        if [ $restart_ornot -eq 0 ]; then

            service fail2ban restart > /dev/null 2>&1

        fi

    fi

Fail2banMenu

}

# checked

ConfigureSSH () {

    # Check if OpenSSH is installed or not
    check=$(grep -o "sshd=YES" < /etc/rc.conf | wc -l | tr -d ' ')
    if [ "$check" -eq 0 ]; then

        if [ ! -e /usr/sbin/sshd ]; then

            dialog --yesno "OpenSSH is not installed on your system, do you want to install it?" 6 44
            sshd_install=$?

            checkInternetConnection

            if [ $sshd_install -eq 0 ]; then

                pkgin -y in opensshd
                # I don't remember if sshd goes automatically to /etc/rc.d/... in case :
                cp /usr/pkg/share/examples/rc.d/sshd /etc/rc.d/sshd

                echo sshd=YES >> /etc/rc.conf

            fi
        fi

    fi


    # Check if a previous configuration has already been done
    if [ -e /etc/ssh/sshd_config.BAK ]; then

        dialog --yesno "A previous configuration seems to have been done\nDo you want to restore the backup file (Yes) or work on the actual configuration? (No)" 7 52
        what_todo=$?

        if [ $what_todo -eq 0 ]; then

            cp /etc/ssh/sshd_config.BAK /etc/ssh/ssh/sshd_config

        fi


    else

        dialog --yesno "Do you want to create a backup of the original /etc/ssh/sshd_config before starting to edit the configuration?\n(you really should say yes!!)" 7 70
        bak_ornot=$?

        if [ $bak_ornot -eq 0 ]; then

            cp /etc/ssh/sshd_config /etc/ssh/sshd_config.BAK

            dialog --msgbox "/etc/ssh/sshd_config has been saved as /etc/ssh/sshd_config.BAK" 5 68

        fi

    fi


    # be guided for configuration or not ?
    dialog --yesno "Do you wish to be guided (Yes) in order to configure SSH properly (with usual parameters)\nor\nDo you prefer to do it yourself? (No)" 8 70
    guided_ornot=$?

    if [ $guided_ornot -eq 0 ]; then

        dialog --msgbox "Then, let's start!" 5 22

        {
            echo "###########################"
            echo "# CUSTOM SSH CONFIGURATION"
            echo " "

        } >> /etc/ssh/sshd_config

        # SSH PORT
        dialog --yesno "Do you want to change the SSH port?\n\nBy default, the SSH port is 22 (TCP)\n(It is recommended to use another port to reduce the risk of automated attacks)" 9 70
        change_port=$?

        if [ $change_port -eq 0 ]; then

            nport=$(dialog --inputbox "Please enter a new port number (>10,000 and <65,000 preferably)" 8 68 2>&1 1>/dev/tty)
            {
                echo "# PORT"
                echo "Port $nport"
                echo " "
            } >> /etc/ssh/sshd_config

            # check if the NPF firewall has already been configured
            if [ -e /etc/npf.conf ]; then

                check=$(npfctl show | grep -o "inactive" | sort | uniq | wc -l | tr -d ' ')
                if [ ! "$check" -eq 1 ]; then

                    dialog --msgbox "The NPF firewall seems to be active\nYou also need to change the SSH port in the rules file to avoid being blocked when SSH is activated.\n\nThe NPF rules file will open\nMake the changes, exit, and save without changing the file location" 11 70

                    pico /etc/npf.conf

                    changePortNPF="1"

                fi


            fi

        else
            {
                echo "# PORT"
                echo "Port 22"
                echo " "
            } >> /etc/ssh/sshd_config

        fi

        # LISTEN ADDRESS
        dialog --yesno "Do you want to configure the listening addresses?\n\n(If your server has multiple network interfaces, it is recommended to specify the IP address(es) of your server on which the SSH service should listen if you do not want users to be able to connect via undesired or protected interfaces)\n\nIf you answer (No), then SSH will listen by default on all interfaces of your server" 13 70
        listen_ip=$?

        if [ $listen_ip -eq 0 ]; then

            echo "# LISTEN ADDRESS" >> /etc/ssh/sshd_config

            i=0
            while [ $i -lt "50" ]; do
                ip_add=$(dialog --inputbox "Please enter an IP address allowed to connect" 8 55 2>&1 1>/dev/tty)
                echo "ListenAddress $ip_add" >> /etc/ssh/sshd_config

                dialog --yesno "Do you want to add another IP?" 5 34
                add_another=$?

                if [ $add_another -eq 1 ]; then

                    i=$((i+51))
                fi

                i=$((i+1))
            done

            echo " " >> /etc/ssh/sshd_config

        else
            {
                echo "# LISTEN ADDRESS"
                echo "ListenAddress 0.0.0.0"
                echo "ListenAddress ::"
            } >> /etc/ssh/sshd_config
        fi

        # AUTHORIZED/ USERS
        dialog --yesno "Do you want to specify the users allowed to connect to this server via SSH?\n(Only the specified users will be allowed to connect)\n\nIf (No), all users will be allowed to connect" 9 70
        user_yesconnect=$?

        if [ $user_yesconnect -eq 0 ]; then

            echo "# ALLOW USERS" >> /etc/ssh/sshd_config

            permitusers=$(dialog --inputbox "Please enter the username(s) of the only user(s) allowed to connect\n(separate usernames with spaces)" 9 70 2>&1 1>/dev/tty)

            echo "AllowUsers ${permitusers}" >> /etc/ssh/sshd_config

            echo " " >> /etc/ssh/sshd_config


        fi

        # DENIED USERS
        dialog --yesno "Do you want to prohibit specific users from connecting to this server via SSH?\n(only the specified users will be prohibited from connecting.\n\nIf you have previously allowed users to connect, then answer (No)" 9 70
        user_noconnect=$?

        if [ $user_noconnect -eq 0 ]; then

            echo "# DENY USERS" >> /etc/ssh/sshd_config

            denyusers=$(dialog --inputbox "Please enter the username(s) of the user(s) denied from connecting\n(separate usernames with spaces)" 9 70 2>&1 1>/dev/tty)

            echo "DenyUsers ${denyusers}" >> /etc/ssh/sshd_config

            echo " " >> /etc/ssh/sshd_config

        fi


        # PERMIT ROOT LOGIN
        dialog --yesno "Do you want to prohibit (Yes) or allow (No) root to connect to this server?\n\n(It is recommended to prohibit root login)" 8 70
        permit_root=$?

        echo "# PERMIT ROOT LOGIN" >> /etc/ssh/sshd_config

        if [ $permit_root -eq 0 ]; then

            echo "PermitRootLogin no" >> /etc/ssh/sshd_config
            echo " " >> /etc/ssh/sshd_config

        else

            echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
            echo " " >> /etc/ssh/sshd_config

        fi


        # PUB KEY AUTHENTICATION
        dialog --yesno "Do you want to allow both key-based and password-based authentication (Yes) or only one of them (No)?\n\nIf you answer (No), you will be prompted to choose on the next screen." 9 70
        pubkey_yesno=$?


        if [ $pubkey_yesno -eq 0 ]; then
            {
                echo "# PUB KEY AND PASSWORD AUTHENTICATION"
                echo "PasswordAuthentication yes"
                echo "AuthorizedKeysFile    .ssh/authorized_keys"
                echo "KbdInteractiveAuthentication yes"
                echo "UsePAM yes"
                echo " "
            } >> /etc/ssh/sshd_config

        else

            dialog --yesno "Do you want to allow only password-based authentication (Yes)\nor\nonly public key-based authentication (No)?\n\nSSH key-based authentication is highly recommended, however, you should not disable password authentication until you have added the public SSH key of the machine that will connect to this server to the /home/USER/.ssh/authorized_keys file on this server. Otherwise, you may risk losing access to the server." 13 70
            pass_orkey=$?

            if [ $pass_orkey -eq 0 ]; then

                {
                    echo "# PASSWORD AUTHENTICATION ONLY"
                    echo "PasswordAuthentication yes"
                    echo "PubkeyAuthentication no"
                    echo "KbdInteractiveAuthentication yes"
                    echo "UsePAM yes"
                    echo " "
                } >> /etc/ssh/sshd_config

            else
                {
                    echo "# PUB KEY AUTHENTICATION ONLY"
                    echo "PasswordAuthentication no"
                    echo "PubkeyAuthentication yes"
                    echo "AuthorizedKeysFile    .ssh/authorized_keys"
                    echo "KbdInteractiveAuthentication no"
                    echo "UsePAM no"
                    echo " "
                } >> /etc/ssh/sshd_config

            fi

        fi



        # X11Forwarding
        dialog --yesno "Do you need to run graphical applications (X11) via SSH?" 5 61
        x11_forward=$?


        if [ $x11_forward -eq 0 ]; then

            {
                echo "# X11 FORWARDING"
                echo "X11Forwarding yes"
                echo " "
            } >> /etc/ssh/sshd_config
        else
            {
                echo "# NO X11 FORWARDING"
                echo "X11Forwarding no"
                echo " "
            } >> /etc/ssh/sshd_config
        fi



        # AllowTcpForwarding
        dialog --yesno "Will you be setting up SSH tunnels?" 5 40
        ssh_tunnels=$?


        if [ $ssh_tunnels -eq 0 ]; then

            {
                echo "# SSH TUNNELING"
                echo "AllowTcpForwarding yes"
                echo " "
            } >> /etc/ssh/sshd_config

        else

            {

                echo "# NO SSH TUNNELING"
                echo "AllowTcpForwarding no"
                echo " "
            } >> /etc/ssh/sshd_config

        fi



        # USER ENVIRONMENT
        dialog --yesno "Will you need to set environment variables via SSH?\n\nIt is recommended not to enable this option." 7 56
        user_env=$?


        if [ $user_env -eq 0 ]; then
            {
                echo "# USER ENVIRONMENT"
                echo "PermitUserEnvironment yes"
                echo " "
            } >> /etc/ssh/sshd_config

        else
            {
                echo "# NO USER ENVIRONMENT"
                echo "PermitUserEnvironment no"
                echo " "
            } >> /etc/ssh/sshd_config

        fi



        # LOGIN GRACE TIME
        dialog --yesno "Do you want to set a timeout during authentication?\n\nIt is recommended to configure a timeout." 7 56
        grace_limit=$?


        if [ $grace_limit -eq 0 ]; then

            timelogin=$(dialog --inputbox "Please enter a timeout value (in seconds)\n(example: 60)" 9 50 2>&1 1>/dev/tty)

            {
                echo "# LOGIN GRACE TIME"
                echo "LoginGraceTime $timelogin"
                echo " "
            } >> /etc/ssh/sshd_config

        fi



        # MAX AUTHENTICATION TRIES
        dialog --yesno "Do you want to limit the number of authentication attempts?\n\n(recommended)" 7 64
        max_ornot=$?


        if [ $max_ornot -eq 0 ]; then

            maxauth=$(dialog --inputbox "Please enter a maximum number of attempts\n(3 or 4 are usually good values)" 9 47 2>&1 1>/dev/tty)

            {
                echo "# MAX AUTHENTICATION TRIES"
                echo "MaxAuthTries $maxauth"
                echo " "
            } >> /etc/ssh/sshd_config

        fi



        # MAX SESSIONS
        dialog --yesno "Do you want to limit the number of simultaneous SSH sessions for each user?\n\n(recommended)" 8 70
        ssh_simul=$?


        if [ $ssh_simul -eq 0 ]; then

            maxsimul=$(dialog --inputbox "Please enter a maximum number of sessions" 8 50 2>&1 1>/dev/tty)

            {
                echo "# MAX SESSIONS PER USER"
                echo "MaxSessions $maxsimul"
                echo " "
            } >> /etc/ssh/sshd_config

        fi




        # AUTOMATIC CLOSING
        dialog --yesno "Do you want to configure automatic closure of inactive sessions?\n\n(recommended)" 7 69
        close_inac=$?

        if [ $close_inac -eq 0 ]; then

            dialog --msgbox "The configuration is done in 2 steps\n\nFirst, you need to define the time (in seconds) between the sending of 2 inactivity requests (example 300)\nThen, we define the maximum number of requests sent before automatic session closure (example 3)\n\nTaking these 2 examples, the connection would be terminated after 15 minutes (300*3)" 13 70
            interval=$(dialog --inputbox "Please enter the maximum number of seconds between the sending of 2 inactivity requests (example 300)" 9 60 2>&1 1>/dev/tty)
            nbrequest=$(dialog --inputbox "Please enter the maximum number of requests sent before session closure (example 3)" 9 60 2>&1 1>/dev/tty)

            {
                echo "# CLOSE INACTIVE SESSIONS"
                echo "ClientAliveInterval $interval"
                echo "ClientAliveCountMax $nbrequest"
                echo " "
            } >> /etc/ssh/sshd_config

        fi



        # SYSLOG FACILITY
        dialog --yesno "Do you want to set SysLogFacility to AUTH?\n\nThis allows SSH messages to be logged appropriately." 7 60
        facility_ornot=$?

        if [ $facility_ornot -eq 0 ]; then

            {
                echo "# SYSLOG FACILITY"
                echo "SyslogFacility AUTH"
                echo " "
            } >> /etc/ssh/sshd_config

        fi



        # LOG LEVEL
        dialog --yesno "Do you want to set the logging level?" 5 42
        level_ornot=$?

        if [ $level_ornot -eq 0 ]; then

            dialog --yesno "Do you want to set it to INFO for normal usage (Yes)\nor\nVERBOSE for more details (No)?" 7 57
            info_verbose=$?

            if [ $info_verbose -eq 0 ]; then

                {
                    echo "# LOG LEVEL"
                    echo "LogLevel INFO"
                    echo " "
                } >> /etc/ssh/sshd_config

            else
                {
                    echo "# LOG LEVEL"
                    echo "LogLevel VERBOSE"
                    echo " "
                } >> /etc/ssh/sshd_config

            fi

        fi




        # DNS
        dialog --yesno "Do you want to disable DNS resolution?\n\nThis speeds up SSH connections and reduces the possibility of DNS-based attacks." 8 70
        dns_ornot=$?

        if [ $dns_ornot -eq 0 ]; then

            {
                echo "# DNS"
                echo "UseDNS no"
                echo " "
            } >> /etc/ssh/sshd_config

        else
            {
                echo "# DNS"
                echo "UseDNS yes"
                echo " "
            } >> /etc/ssh/sshd_config
        fi




        # SFTP
        dialog --yesno "Will you be using the SFTP protocol (FTP over SSH) for file exchange via SSH?" 6 66
        sftp_ornot=$?

        if [ $sftp_ornot -eq 0 ]; then

            dialog --yesno "Do you want to use /usr/libexex/sftp-server (default choice) (Yes)\nor\ninternal-sftp (No)?" 7 70
            which_sftp=$?

            if [ $which_sftp -eq 0 ]; then
                {
                    echo "# SFTP"
                    echo "Subsystem     sftp    /usr/libexec/sftp-server"
                    echo " "
                } >> /etc/ssh/sshd_config
            else
                {
                    echo "# SFTP"
                    echo "Subsystem     sftp    internal-sftp"
                    echo " "
                } >> /etc/ssh/sshd_config
            fi

        fi



        # MOTD
        dialog --yesno "Do you want to disable the Message of the Day (Motd)?\n\n(recommended)" 7 58
        motd_ornot=$?

        if [ $motd_ornot -eq 0 ]; then
            {
                echo "# MOTD"
                echo "PrintMotd no"
                echo " "
            } >> /etc/ssh/sshd_config
        else
            {
                echo "# MOTD"
                echo "PrintMotd yes"
                echo " "
            } >> /etc/ssh/sshd_config
        fi




        # LAST LOG
        dialog --yesno "Do you want to hide (Yes) or display (No) the message showing the date and time of the last login when a user logs in?\n\n(It is recommended to hide this information)" 8 70
        hidelog_ornot=$?

        if [ $hidelog_ornot -eq 0 ]; then
            {
                echo "# PRINT LAST LOG"
                echo "PrintLastLog no"
                echo " "
            } >> /etc/ssh/sshd_config
        else
            {
                echo "# PRINT LAST LOG"
                echo "PrintLastLog yes"
                echo " "
            } >> /etc/ssh/sshd_config
        fi

        # USUAL
        {
            echo "# DISABLE HPN"
            echo "HPNDisabled yes"
            echo " "
        } >> /etc/ssh/sshd_config

        dialog --msgbox "The configuration is now completed" 5 39

    else

        dialog --msgbox "/etc/ssh/sshd_config is going to be opened in a text editor in order to let you configure SSH yourself\n\nDo what you need to do, then Exit and Save without changing the location of the file\n\nYou'll be asked to activate (or not) the configuration at the end" 11 69

        pico /etc/ssh/sshd_config


        # check if Port is commented or not
        check=$(grep Port < /etc/ssh/sshd_config | grep "[0-9]" | grep -o '#' | sort | uniq | wc -l | tr -d ' ')

        if [ "$check" -eq 0 ]; then

            # check if Port has been modified
            check2=$(grep -o "Port 22" < /etc/ssh/sshd_config | sort | uniq | wc -l | tr -d ' ')
            if [ ! "$check2" -eq 1 ]; then

                # check if the NPF firewall has already been configured
                if [ -e /etc/npf.conf ]; then

                    # check if NPF is running
                    check=$(npfctl show | grep -o "inactive" | sort | uniq | wc -l | tr -d ' ')
                    if [ ! "$check" -eq 1 ]; then

                        dialog --msgbox "The NPF firewall seems to be active\nYou also need to change the SSH port in the rules file to avoid being blocked when SSH is activated.\n\nThe NPF rules file will open\nMake the changes, exit, and save without changing the file location" 11 70

                        pico /etc/npf.conf

                        changePortNPF="1"

                    fi


                fi

            fi

        fi

    fi

        dialog --yesno "Do you want to (re)start SSH?" 5 33
        activate_ornot=$?

    if [ $activate_ornot -eq 0 ]; then

        service sshd restart > /dev/null 2>&1

        sleep 1

        check=$(service sshd status | grep -o "sshd is not running." | wc -l | tr -d)

        if [ "$check" -eq 0 ]; then
            dialog --msgbox "It seems that something went wrong, sshd did not start" 5 59

        fi

        if [ "$changePortNPF" -eq 1 ]; then

            dialog --yesno "You have modified the SSH port, do you want to restart the firewall now?" 6 66
            restart_npf=$?

            if [ $restart_npf -eq 0 ]; then

                service npf restart > /dev/null 2>&1

            fi


        fi

        check=$(service sshd status | grep -o "sshd is running" | wc -l | tr -d ' ')

        if [ "$check" -eq 1 ]; then
            dialog --msgbox "SSH is running, Congratulations!" 5 36
        fi


    fi

    SecurityMenu

}

# checked

FormatToNTFS () {

    {

    ################################################
    # STAGE 0 : CHECK FOR NECESSARY TOOLS

        if [ ! -e /usr/pkg/sbin/mkntfs ]; then
            checkInternetConnection

            pkgin -y in fuse > /dev/null 2>&1
            echo 20
            pkgin -y in fuse-ntfs > /dev/null 2>&1
            echo 40
            pkgin -y in fuse-ntfs-3g > /dev/null 2>&1
            echo 60
            pkgin -y in libntfs > /dev/null 2>&1
            echo 80
            pkgin -y inntfsprogs > /dev/null 2>&1
            echo 100

        fi


    } | dialog --gauge "Checking for necessary software..." 6 39

    dialog --msgbox "If you have just inserted the USB device, then you can continue. Otherwise, please unplug it, wait a few seconds, then plug it back in, wait a few seconds, and then continue" 7 70

    ################################################
    # STAGE 1 : DETECTION AND CHOICE OF THE DEVICE

    # Create a temporary file
    TMPFILE=$(mktemp)

    # Generate the list of devices
    dmesg | tail -5 | grep -o "sd[0-9]" | sort | uniq > "$TMPFILE"

    # Check if the list is empty
    if [ ! -s "$TMPFILE" ]; then
        dialog --msgbox "No USB devices detected" 5 30
        rm -f "$TMPFILE"
        DiskMngmtMenu
    fi

    # Read the temporary file and construct the option for dialog
    devices=""
    while IFS= read -r line; do
        devices="$devices $line \"$line\" off"
    done < "$TMPFILE"

    # Use dialog to display the list of devices
    device=$(eval "dialog --radiolist \"Choose the USB device to format\" 0 0 0 $devices 3>&1 1>&2 2>&3")

    # Clean up and remove the temporary file
    rm -f "$TMPFILE"

    ###################################################################################################################
    # STAGE 2 : CHECK IF THE DEVICE IS ASSOCIATED TO A GEOMETRY AND IF THIS GEOMETRY IS ALREADY MOUNTED ON THE SYSTEM

    # check if already mounted then format
    if [ -n "$device" ]; then

        # check if the selected device is already associated with a geometry
        seekdkX=$(dmesg | tail -10 | grep "${device}" | grep -o "dk[0-9]" | sort | uniq | wc -l | tr -d ' ')

        if [ "$seekdkX" -gt 0 ]; then

            # get geom name (dkX)
            getgeom=$(dmesg | tail -10 | grep "${device}" | grep -o "dk[0-9]" | sort | uniq)
            checkmounted=$(mount | grep -o "/dev/${getgeom}" | sort | uniq | wc -l | tr -d ' ')

            if [ "$checkmounted" -eq 1 ]; then

                dialog --msgbox "The device is mounted, please unmount it first" 5 50
                DiskMngmtMenu

            fi

        fi

        {

    ###################
    # STAGE 3 : FORMAT

            # Destroy and Create a new GPT table
            gpt destroy "$device" > /dev/null 2>&1
            gpt create -f "$device" > /dev/null 2>&1

            echo 10

            # Create a partition of type windows
            gpt add -t windows "$device" > /dev/null 2>&1

            echo 20

            # The operation is repeated a second time to accommodate the transition from MBR to GPT (again, it is needed sometimes)
            gpt destroy "$device" > /dev/null 2>&1
            gpt create -f "$device" > /dev/null 2>&1

            echo 30

            # Create a partition of type windows
            gpt add -t windows "$device" > /dev/null 2>&1

            echo 40

            # Retrieve the created geometry:
            geom=$(dmesg | tail -5 | grep "${device}" | grep -o "dk[0-9]" | sort | uniq | tr -d ' ')

            # Create the filesystem:
            mkntfs -f "/dev/$geom" > /dev/null 2>&1

            echo 100


        } | dialog --gauge "Formatting in progress..." 6 31

        geom=$(dmesg | tail -5 | grep -o "dk[0-9]" | sort | uniq | tr -d ' ')


    ##############################################
    # STAGE 4 : MOUNT THE NEWLY CREATED GEOMETRY

        dialog --yesno "Do you want to mount the USB device to /media/$geom?" 5 56
        mount_ornot=$?

        if [ "$mount_ornot" -eq 0 ]; then

            # Creating the mount point
            mkdir -p /media/"$geom" > /dev/null 2>&1

            # Mounting NTFS
            env PERFUSE_BUFSIZE=135168 ntfs-3g /dev/"$geom" /media/"$geom" > /dev/null 2>&1

            dialog --msgbox "Don't forget about permissions on /media/$geom" 5 51

        fi

        DiskMngmtMenu


    fi
}

# checked

FormatToEXFAT () {

    {

    ################################################
    # STAGE 0 : CHECK FOR NECESSARY TOOLS

        if [ ! -e /usr/pkg/sbin/mkexfatfs ]; then
            checkInternetConnection

            pkgin -y in fuse > /dev/null 2>&1
            echo 20
            pkgin -y in fuse-ntfs > /dev/null 2>&1
            echo 40
            pkgin -y in fuse-ntfs-3g > /dev/null 2>&1
            echo 60
            pkgin -y in libntfs > /dev/null 2>&1
            echo 70
            pkgin -y fuse-exfat > /dev/null 2>&1
            echo 80
            pkgin -y inntfsprogs > /dev/null 2>&1
            echo 100

        fi


    } | dialog --gauge "Checking for necessary software..." 6 39

    dialog --msgbox "If you have just inserted the USB device, then you can continue. Otherwise, please unplug it, wait a few seconds, then plug it back in, wait a few seconds, and then continue" 7 70

    ################################################
    # STAGE 1 : DETECTION AND CHOICE OF THE DEVICE

    # Create a temporary file
    TMPFILE=$(mktemp)

    # Generate the list of devices
    dmesg | tail -5 | grep -o "sd[0-9]" | sort | uniq > "$TMPFILE"

    # Check if the list is empty
    if [ ! -s "$TMPFILE" ]; then
        dialog --msgbox "No USB devices detected" 5 30
        rm -f "$TMPFILE"
        DiskMngmtMenu
    fi

    # Read the temporary file and construct the option for dialog
    devices=""
    while IFS= read -r line; do
        devices="$devices $line \"$line\" off"
    done < "$TMPFILE"

    # Use dialog to display the list of devices
    device=$(eval "dialog --radiolist \"Choose the USB device to format\" 0 0 0 $devices 3>&1 1>&2 2>&3")

    # Clean up and remove the temporary file
    rm -f "$TMPFILE"

    ###################################################################################################################
    # STAGE 2 : CHECK IF THE DEVICE IS ASSOCIATED TO A GEOMETRY AND IF THIS GEOMETRY IS ALREADY MOUNTED ON THE SYSTEM

    # check if already mounted then format
    if [ -n "$device" ]; then

        # check if the selected device is already associated with a geometry
        seekdkX=$(dmesg | tail -10 | grep "${device}" | grep -o "dk[0-9]" | sort | uniq | wc -l | tr -d ' ')

        if [ "$seekdkX" -gt 0 ]; then

            # get geom name (dkX)
            getgeom=$(dmesg | tail -10 | grep "${device}" | grep -o "dk[0-9]" | sort | uniq)
            checkmounted=$(mount | grep -o "/dev/${getgeom}" | sort | uniq | wc -l | tr -d ' ')

            if [ "$checkmounted" -eq 1 ]; then

                dialog --msgbox "The device is mounted, please unmount it first" 5 50
                DiskMngmtMenu

            fi

        fi

        {

    ###################
    # STAGE 3 : FORMAT

            # Destroy and Create a new GPT table
            gpt destroy "$device" > /dev/null 2>&1
            gpt create -f "$device" > /dev/null 2>&1

            echo 10

            # Create a partition of type windows
            gpt add -t windows "$device" > /dev/null 2>&1

            echo 20

            # The operation is repeated a second time to accommodate the transition from MBR to GPT (again, it is needed sometimes)
            gpt destroy "$device" > /dev/null 2>&1
            gpt create -f "$device" > /dev/null 2>&1

            echo 30

            # Create a partition of type windows
            gpt add -t windows "$device" > /dev/null 2>&1

            echo 40

            # Retrieve the created geometry:
            geom=$(dmesg | tail -5 | grep "${device}" | grep -o "dk[0-9]" | sort | uniq | tr -d ' ')

            # Create the filesystem:
            /usr/pkg/sbin/mkexfatfs "/dev/$geom" > /dev/null 2>&1

            echo 100


        } | dialog --gauge "Formatting in progress..." 6 31

        geom=$(dmesg | tail -5 | grep -o "dk[0-9]" | sort | uniq | tr -d ' ')

        ##############################################
        # STAGE 4 : MOUNT THE NEWLY CREATED GEOMETRY

        dialog --yesno "Do you want to mount the USB device to /media/$geom?" 5 56
        mount_ornot=$?

        if [ "$mount_ornot" -eq 0 ]; then

            # Creating the mount point
            mkdir -p /media/"$geom" > /dev/null 2>&1

            # Mounting
            env PERFUSE_BUFSIZE=135168 /usr/pkg/sbin/mount.exfat /dev/"$geom" /media/"$geom" > /dev/null 2>&1
            #env PERFUSE_BUFSIZE=135168 ntfs-3g /dev/$geom /media/$geom > /dev/null 2>&1

            dialog --yesno "Don't you want to give Read/Write permissions to a user on /media/$geom?" 6 60
            rw_ornot=$?
            if [ $rw_ornot -eq 0 ]; then

                user=$(dialog --title "Read/Write Permissions" --inputbox "Please enter the username" 8 40 2>&1 1>/dev/tty)
                /sbin/chown -R "$user" /media/"$geom"
                chmod -R /media/"$geom"

            else

                dialog --msgbox "Don't forget about permissions on /media/$geom" 5 51

            fi

       fi

        DiskMngmtMenu

    fi

}

# checked

FormatToFFSv1 () {

    dialog --yesno "FFSv1 is outdated and does not support storage devices > 1 TB. Do you want to continue?" 6 67
    ffsv1_choix=$?

    case $ffsv1_choix in
        1)
            DiskMngmtMenu
        ;;
    esac

    dialog --msgbox "If you have just inserted the USB device, then you can continue. Otherwise, please unplug it, wait a few seconds, then plug it back in, wait a few seconds, and then continue" 7 70

    ################################################
    # STAGE 1 : DETECTION AND CHOICE OF THE DEVICE

    # Create a temporary file
    TMPFILE=$(mktemp)

    # Generate the list of devices
    dmesg | tail -5 | grep -o "sd[0-9]" | sort | uniq > "$TMPFILE"

    # Check if the list is empty
    if [ ! -s "$TMPFILE" ]; then
        dialog --msgbox "No USB devices detected" 5 30
        rm -f "$TMPFILE"
        DiskMngmtMenu
    fi

    # Read the temporary file and construct the option for dialog
    devices=""
    while IFS= read -r line; do
        devices="$devices $line \"$line\" off"
    done < "$TMPFILE"

    # Use dialog to display the list of devices
    device=$(eval "dialog --radiolist \"Choose the USB device to format\" 0 0 0 $devices 3>&1 1>&2 2>&3")

    # Clean up and remove the temporary file
    rm -f "$TMPFILE"

    ###################################################################################################################
    # STAGE 2 : CHECK IF THE DEVICE IS ASSOCIATED TO A GEOMETRY AND IF THIS GEOMETRY IS ALREADY MOUNTED ON THE SYSTEM

    # check if already mounted then format
    if [ -n "$device" ]; then

        # check if the selected device is already associated with a geometry
        seekdkX=$(dmesg | tail -10 | grep "${device}" | grep -o "dk[0-9]" | sort | uniq | wc -l | tr -d ' ')

        if [ "$seekdkX" -gt 0 ]; then

            # get geom name (dkX)
            getgeom=$(dmesg | tail -10 | grep "${device}" | grep -o "dk[0-9]" | sort | uniq)
            checkmounted=$(mount | grep -o "/dev/${getgeom}" | sort | uniq | wc -l | tr -d ' ')

            if [ "$checkmounted" -eq 1 ]; then

                dialog --msgbox "The device is mounted, please unmount it first" 5 50
                DiskMngmtMenu

            fi

        fi

        {

    ###################
    # STAGE 3 : FORMAT

            # Destroy and Create a new GPT table
            gpt destroy "$device" > /dev/null 2>&1
            gpt create -f "$device" > /dev/null 2>&1

            echo 10

            # Destroy and Create a new GPT table again
            gpt destroy "$device" > /dev/null 2>&1
            gpt create -f "$device" > /dev/null 2>&1

            echo 20

            # Create a partition of type FFS
            gpt add -t ffs "$device" > /dev/null 2>&1

            echo 30

            # Retrieve the created geometry:
            geom=$(dmesg | tail -5 | grep "${device}" | grep -o "dk[0-9]" | sort | uniq | tr -d ' ')

            # Create the filesystem:
            newfs -O1 "$geom" > /dev/null 2>&1

            echo 100

        } | dialog --gauge "Formatting in progress..." 6 31

    ##############################################
    # STAGE 4 : MOUNT THE NEWLY CREATED GEOMETRY

        geom=$(dmesg | tail -5 | grep "${device}" | grep -o "dk[0-9]" | sort | uniq | tr -d ' ')

        dialog --yesno "Do you want to mount the USB device to /media/$geom?" 5 56
        mount_ornot=$?

        if [ $mount_ornot -eq 0 ]; then

            # Création du point de montage
            mkdir -p /media/"$geom" > /dev/null 2>&1

            # Montage
            mount /dev/"$geom" /media/"$geom" > /dev/null 2>&1

            dialog --yesno "Don't you want to give Read/Write permissions to a user on /media/$geom?" 6 60
            rw_ornot=$?
            if [ $rw_ornot -eq 0 ]; then

                user=$(dialog --title "Read/Write Permissions" --inputbox "Please enter the username" 8 40 2>&1 1>/dev/tty)
                /sbin/chown -R "$user" /media/"$geom"
                chmod -R /media/"$geom"

            else

                dialog --msgbox "Don't forget about permissions on /media/$geom" 5 51

            fi

        fi

        DiskMngmtMenu

	fi

}

# checked

FormatToFFSv2 () {

    dialog --msgbox "If you have just inserted the USB device, then you can continue. Otherwise, please unplug it, wait a few seconds, then plug it back in, wait a few seconds, and then continue" 7 70

    ################################################
    # STAGE 1 : DETECTION AND CHOICE OF THE DEVICE

    # Create a temporary file
    TMPFILE=$(mktemp)

    # Generate the list of devices
    dmesg | tail -5 | grep -o "sd[0-9]" | sort | uniq > "$TMPFILE"

    # Check if the list is empty
    if [ ! -s "$TMPFILE" ]; then
        dialog --msgbox "No USB devices detected" 5 30
        rm -f "$TMPFILE"
        DiskMngmtMenu
    fi

    # Read the temporary file and construct the option for dialog
    devices=""
    while IFS= read -r line; do
        devices="$devices $line \"$line\" off"
    done < "$TMPFILE"

    # Use dialog to display the list of devices
    device=$(eval "dialog --radiolist \"Choose the USB device to format\" 0 0 0 $devices 3>&1 1>&2 2>&3")

    # Clean up and remove the temporary file
    rm -f "$TMPFILE"

    ###################################################################################################################
    # STAGE 2 : CHECK IF THE DEVICE IS ASSOCIATED TO A GEOMETRY AND IF THIS GEOMETRY IS ALREADY MOUNTED ON THE SYSTEM

    # check if already mounted then format
    if [ -n "$device" ]; then

        # check if the selected device is already associated with a geometry
        seekdkX=$(dmesg | tail -10 | grep "${device}" | grep -o "dk[0-9]" | sort | uniq | wc -l | tr -d ' ')

        if [ "$seekdkX" -gt 0 ]; then

            # get geom name (dkX)
            getgeom=$(dmesg | tail -10 | grep "${device}" | grep -o "dk[0-9]" | sort | uniq)
            checkmounted=$(mount | grep -o "/dev/${getgeom}" | sort | uniq | wc -l | tr -d ' ')

            if [ "$checkmounted" -eq 1 ]; then

                dialog --msgbox "The device is mounted, please unmount it first" 5 50
                DiskMngmtMenu

            fi

        fi

        {

    ###################
    # STAGE 3 : FORMAT

            # Destroy and Create a new GPT table
            gpt destroy "$device" > /dev/null 2>&1
            gpt create -f "$device" > /dev/null 2>&1

            echo 10

            # Destroy and Create a new GPT table again
            gpt destroy "$device" > /dev/null 2>&1
            gpt create -f "$device" > /dev/null 2>&1

            echo 20

            # Create a partition of type FFS
            gpt add -t ffs "$device" > /dev/null 2>&1

            echo 30

            # Retrieve the created geometry:
            geom=$(dmesg | tail -5 | grep "${device}" | grep -o "dk[0-9]" | sort | uniq | tr -d ' ')

            # Create the filesystem:
            newfs -O2 "$geom" > /dev/null 2>&1

            echo 100

        } | dialog --gauge "Formatting in progress..." 6 30

    ##############################################
    # STAGE 4 : MOUNT THE NEWLY CREATED GEOMETRY

        geom=$(dmesg | tail -5 | grep "${device}" | grep -o "dk[0-9]" | sort | uniq | tr -d ' ')

        dialog --yesno "Do you want to mount the USB device to /media/$geom?" 5 56
        mount_ornot=$?

        if [ "$mount_ornot" -eq 0 ]; then

            # Création du point de montage
            mkdir -p /media/"$geom" > /dev/null 2>&1

            # Montage
            mount /dev/"$geom" /media/"$geom" > /dev/null 2>&1

            dialog --yesno "Don't you want to give Read/Write permissions to a user on /media/$geom?" 6 60
            rw_ornot=$?
            if [ "$rw_ornot" -eq 0 ]; then

                user=$(dialog --title "Read/Write Permissions" --inputbox "Please enter the username" 8 40 2>&1 1>/dev/tty)
                /sbin/chown -R "$user" /media/"$geom"
                chmod -R /media/"$geom"

            else

                dialog --msgbox "Don't forget about permissions on /media/$geom" 5 51

            fi

        fi

        DiskMngmtMenu

	fi

}

# checked

mountUSB () {

    dialog --msgbox "If you have just inserted the USB device, then you can continue. Otherwise, please unplug it, wait a few seconds, then plug it back in, wait a few seconds, and then continue" 7 70

    count=$(dmesg | tail -5 | grep -o ntfs | wc -l | tr -d " ")

    if [ "$count" -gt 0 ]; then

        device=$(dmesg | tail -5 | grep "ntfs" | grep -o "dk[0-9]" | sort | uniq)
        checkmounted=$(mount | grep -o "/dev/$device" | sort | uniq | wc -l | tr -d ' ')

        if [ "$checkmounted" -eq 1 ]; then
            dialog --msgbox "Device already mounted on /dev/$dkX" 5 41
        else
            if [ -n "$device" ]; then
                # if NTFS
                env PERFUSE_BUFSIZE=135168 ntfs-3g /dev/"$device" /media/"$device"
                # if ExFAT :
                env PERFUSE_BUFSIZE=135168 /usr/pkg/sbin/mount.exfat /dev/"$device" /media/"$device"

            else
                dialog --msgbox "No NTFS-associated device dkX found." 5 40
            fi
        fi

    else
        dkX=$(dmesg | tail -10 | grep -o "dk[0-9]")
        checkdkX=$(dmesg | tail -10 | grep -o "dk[0-9]" | sort | uniq | wc -l | tr -d ' ')

        if [ "$checkdkX" -eq 0 ]; then

            dialog --msgbox "Device not detected" 5 23
            DiskMngmtMenu

        fi

        checkmounted=$(mount | grep -o "/dev/$dkX" | sort | uniq | wc -l | tr -d ' ')
        if [ "$checkmounted" -eq 1 ]; then
            dialog --msgbox "Device already mounted on /dev/$dkX" 5 41
            DiskMngmtMenu
        else
            mount /dev/"$dkX" /media/"$dkX"

        fi
    fi

    dialog --yesno "Don't you want to give Read/Write permissions to a user on /media/$device?" 6 60
    rw_ornot=$?
    if [ "$rw_ornot" -eq 0 ]; then

        user=$(dialog --title "Read/Write Permissions" --inputbox "Please enter the username" 8 40 2>&1 1>/dev/tty)
        /sbin/chown -R "$user" /media/"$dkX"
        chmod -R /media/"$dkX"

    else

        dialog --msgbox "Don't forget about permissions on /media/$dkX" 5 51

    fi

    DiskMngmtMenu
}

# checked


umountUSB () {
    # Create a temporary file
    TMPFILE=$(mktemp)

    # Generate the list of devices
    mount | grep media | grep -o "dk[0-9]" | sort | uniq > "$TMPFILE"

    # Check if the list is empty
    if [ ! -s "$TMPFILE" ]; then
        dialog --msgbox "No mounted USB devices detected" 5 35
        rm -f "$TMPFILE"
        DiskMngmtMenu
        return
    fi

    # Read the temporary file and construct the option for dialog
    devices=""
    while IFS= read -r line; do
        devices="$devices $line \"$line\" off"
    done < "$TMPFILE"

    # Use dialog to display the list of devices
    device=$(eval "dialog --radiolist \"Choose the USB device to unmount\" 0 0 0 $devices 3>&1 1>&2 2>&3")

    # Clean up and remove the temporary file
    rm -f "$TMPFILE"

    # Unmount the selected device
    if [ -n "$device" ]; then
        umount -f "/media/$device" || dialog --msgbox "Error unmounting /media/$device" 5 33
    fi

    # Return to disk management menu
    DiskMngmtMenu

}

# checked

BurnISOtoUSB () {

    dialog --msgbox "If you have just inserted the USB device, then you can continue. Otherwise, please unplug it, wait a few seconds, then plug it back in, wait a few seconds, and then continue" 7 70

    # Verifications
    seekdkX=$(dmesg | tail -10 | grep "sd[0-9]" | grep -o "dk[0-9]" | sort | uniq)

    for each in $seekdkX; do

        checkmounted=$(mount | grep -o "/dev/$each" | sort | uniq | wc -l | tr -d ' ')

        if [ "$checkmounted" -eq 1 ]; then

            dialog --msgbox "The device is mounted, please unmount it first" 5 50
            DiskMngmtMenu

        fi
    done


    # Create a temporary file
    TMPFILE=$(mktemp)

    # Generate the list of devices
    sysctl hw.disknames | grep -o "sd[0-9]" | sort | uniq > "$TMPFILE"

    # Check if the list is empty
    if [ ! -s "$TMPFILE" ]; then
        dialog --msgbox "No USB devices detected" 5 32
        rm -f "$TMPFILE"
        DiskMngmtMenu
    fi

    # Read the temporary file and construct the option for dialog
    devices=""
    while IFS= read -r line; do
        devices="$devices $line \"$line\" off"
    done < "$TMPFILE"

    # Use dialog to display the list of devices
    device=$(eval "dialog --radiolist \"Choose the USB device to burn ISO\" 0 0 0 $devices 3>&1 1>&2 2>&3")

    # Clean up and remove the temporary file
    rm -f "$TMPFILE"

    # Burn the .iso image
    if [ -n "$device" ]; then

        isoFile=$(dialog --title "ISO file" --inputbox "Please enter the absolute path of your .iso file" 9 54 2>&1 1>/dev/tty)
        {
            dd if="$isoFile" of=/dev/"$device" bs=8m msgfmt=human

        } | dialog --gauge "Writing in progress..." 6 26
    fi

    # Return to disk management menu
    DiskMngmtMenu

}

# checked

BurnISOtoCD () {

    checkInternetConnection

    {

        pkgin -y in cdrtools > /dev/null 2>&1

        echo 100

    } | dialog --gauge "Checking for necessary software..." 6 39


    # Create a temporary file
    TMPFILE=$(mktemp)

    # Generate the list of devices
    # grep -v "*" is not a glob ! It's necessary to keep only the bus actually connected
    cdrecord --scanbus | grep "[0-9],[0-9],[0-9]" | sed "/\*/d" | grep -o "[0-9],[0-9],[0-9]" | sort | uniq > "$TMPFILE"

    # Check if the list is empty
    if [ ! -s "$TMPFILE" ]; then
        dialog --msgbox "No burner detected..." 5 32
        rm -f "$TMPFILE"
        DiskMngmtMenu
    fi

    # Read the temporary file and construct the option for dialog
    devices=""
    while IFS= read -r line; do
        devices="$devices $line \"$line\" off"
    done < "$TMPFILE"

    # Use dialog to display the list of devices
    device=$(eval "dialog --radiolist \"Choose the burner\" 0 0 0 $devices 3>&1 1>&2 2>&3")

    # Clean up and remove the temporary file
    rm -f "$TMPFILE"

    # Burn the .iso image
    if [ -n "$device" ]; then

        isoFile=$(dialog --title "ISO file" --inputbox "Please enter the absolute path of your .iso file" 9 54 2>&1 1>/dev/tty)

    if [ ! -e "${isoFile}" ]; then

        dialog --msgbox "File does not exist" 5 23
        DiskMngmtMenu

    fi
        {
            cdrecord dev="${device}" -v "${isoFile}" > /dev/null 2>&1

            echo 100

        } | dialog --gauge "Writing in progress..." 6 26

        TMPFILE=$(mktemp)

        dialog --yesno "Do you want to verify if the burning was done correctly?" 5 61
        burn_ok=$?

        if [ "$burn_ok" -eq 0 ]; then

            readcd dev="${device}" f=/tmp/diskburnedTMP.iso > /dev/null 2>&1
            sleep 1
            check=$(cmp "${isoFile}" /tmp/diskburnedTMP.iso | sort | uniq | wc -l | tr -d ' ')


            if [ "$check" -eq 0 ]; then

                dialog --msgbox "The burning process was successful" 5 38
                rm /tmp/diskburnedTMP.iso

            fi

        fi


    fi

    # Return to disk management menu
    DiskMngmtMenu

}

# checked

SecurelyErase () {

    dialog --msgbox "If you have just inserted the USB device, then you can continue. Otherwise, please unplug it, wait a few seconds, then plug it back in, wait a few seconds, and then continue" 7 70

    # Verifications
    seekdkX=$(dmesg | tail -10 | grep "sd[0-9]" | grep -o "dk[0-9]" | sort | uniq)

    for each in $seekdkX; do

        checkmounted=$(mount | grep -o "/dev/$each" | sort | uniq | wc -l | tr -d ' ')

        if [ "$checkmounted" -eq 1 ]; then

            dialog --msgbox "The device is mounted, please unmount it first" 5 50
            DiskMngmtMenu

        fi
    done


    # Create a temporary file
    TMPFILE=$(mktemp)

    # Generate the list of devices
    sysctl hw.disknames | grep -o "sd[0-9]" | sort | uniq > "$TMPFILE"

    # Check if the list is empty
    if [ ! -s "$TMPFILE" ]; then
        dialog --msgbox "No USB devices detected" 5 32
        rm -f "$TMPFILE"
        DiskMngmtMenu
    fi

    # Read the temporary file and construct the option for dialog
    devices=""
    while IFS= read -r line; do
        devices="$devices $line \"$line\" off"
    done < "$TMPFILE"

    # Use dialog to display the list of devices
    device=$(eval "dialog --radiolist \"Choose the USB device to burn ISO\" 0 0 0 $devices 3>&1 1>&2 2>&3")

    # Clean up and remove the temporary file
    rm -f "$TMPFILE"

    # Erase the device
    if [ -n "$device" ]; then
        {
            dd if=/dev/zero of=/dev/"$device" bs=8m msgfmt=human

            echo 100

        } | dialog --gauge "Erasing in progress..." 6 26
    fi

    # Return to disk management menu
    DiskMngmtMenu

}

# checked

RestartDHCP () {

    service dhcpcd restart > /dev/null 2>&1

    NetworkMenu

}

# checked

SwitchToWifi () {


    # Create a temporary file
    TMPFILE=$(mktemp)

    # Get NICs
    netstat -i | cut -d' ' -f1 | grep -v "Name" | grep -v "lo0" | grep -v "npflo" | tr -d '*' | sort | uniq > "$TMPFILE"

    # Check if the list is empty
    if [ ! -s "$TMPFILE" ]; then
        dialog --msgbox "No NIC detected" 5 30
        rm -f "$TMPFILE"
        NetworkMenu
    fi

    # Read the temporary file and construct the option for dialog
    devices=""
    while IFS= read -r line; do
        devices="$devices $line \"$line\" off"
    done < "$TMPFILE"

    # Use dialog to display the list of devices
    device=$(eval "dialog --radiolist \"Choose the Wifi NIC please\" 0 0 0 $devices 3>&1 1>&2 2>&3")

    # Clean up and remove the temporary file
    rm -f "$TMPFILE"

    # choice of the user :
    #echo $device


    {
        # Enabling dhcpcd at startup
        check=$(grep -o 'dhcpcd=' < /etc/rc.conf | sort | uniq | wc -l | tr -d ' ')
        if [ "$check" -eq 1 ]; then
                sed -i 's/dhcpcd=NO/dhcpcd=YES/' /etc/rc.conf
                sed -i 's/#dhcpcd=YES/dhcpcd=YES/' /etc/rc.conf
                sed -i 's/#dhcpcd=NO/dhcpcd=YES/' /etc/rc.conf
        else
                echo dhcpcd=YES >> /etc/rc.conf
        fi

        echo 16

        # Setting up wifi NIC flags for dhcpcd
        FILE="/etc/rc.conf"

        # Check if the dhcpcd_flags entry exists and contains "-qM wm0" but not "${device}"
        if grep -q "^dhcpcd_flags=.*-qM wm0" "$FILE" && ! grep -q "^dhcpcd_flags=.*${device}" "$FILE"; then
            # Use sed to add wifi NIC after "-qM wm0"
            sed -i'' -e "/^dhcpcd_flags=.*-qM wm0/s/-qM wm0/& ${device}/" "$FILE"
        fi

        # Restart dhcpcd
        service dhcpcd restart > /dev/null 2>&1

        echo 32

        # Change the WAN interface in the firewall rules file
        FILE="/etc/npf.conf"

        # Replace "wm0" with the wifi NIC in specific lines
        if [ -f "$FILE" ]; then
            sed -i'' -e "/^\$WAN_if = \"wm0\"/s/wm0/${device}/" -e "/^\$WAN_addrs = ifaddrs(wm0)/s/wm0/${device}/" "$FILE"
            # Restart the firewall
            service npf restart > /dev/null 2>&1
        fi


        echo 48


        # Activation of wifi NIC at startup
        check=$(grep -o "ifconfig_${device}=" < /etc/rc.conf | sort | uniq  | wc -l | tr -d ' ')
        if [ "$check" -eq 1 ]; then
            sed -i "s/ifconfig_${device}=\"down\"/ifconfig_${device}=\"up\"/" /etc/rc.conf
            sed -i "s/#ifconfig_${device}=\"up\"/ifconfig_${device}=\"up\"/" /etc/rc.conf
            sed -i "s/#ifconfig_${device}=\"down\"/ifconfig_${device}=\"up\"/" /etc/rc.conf
        else
            echo "ifconfig_${device}=\"up\"" >> /etc/rc.conf
        fi

        # Starting the wifi NIC interface
        ifconfig "${device}" up > /dev/null 2>&1
        sleep 3

        echo 64

        # Activation of wpa_supplicant at startup
        check=$(grep -o 'wpa_supplicant=' < /etc/rc.conf | sort | uniq | wc -l | tr -d ' ')
        if [ "$check" -eq 1 ]; then
            sed -i 's/wpa_supplicant=NO/wpa_supplicant=YES/' /etc/rc.conf
            sed -i 's/#wpa_supplicant=YES/wpa_supplicant=YES/' /etc/rc.conf
            sed -i 's/#wpa_supplicant=NO/wpa_supplicant=YES/' /etc/rc.conf
        else
            echo "wpa_supplicant=YES" >> /etc/rc.conf
        fi

        echo 80

        # Starting wpa_supplicant
        service wpa_supplicant restart > /dev/null 2>&1
        sleep 3


        echo 100


    } | dialog --gauge "Enabling Wifi..." 6 21 0

    dialog --msgbox "Wifi Enabled" 5 16

    NetworkMenu
}


ConnectWifi () {

    check=$(service wpa_supplicant status| grep -o 'wpa_supplicant is running' | sort | uniq | wc -l | tr -d ' ')
    if [ "$check" -eq 0 ]; then

        dialog --yesno "WPA supplicant is not running\n\nWould you like to go to 'Switch from Ethernet to Wifi' function (Yes)\nor\nJust activate WPA temporary and do what you want? (No)" 10 70
        switch_ornot=$?

        if [ $switch_ornot -eq 0 ]; then

            SwitchToWifi

        else

            service wpa_supplicant onestart > /dev/null 2>&1

        fi


    fi


    {
        # Network scan
        wpa_cli scan
        sleep 3
        echo 20
        sleep 3
        echo 40
        sleep 3
        echo 60
        sleep 2
        echo 80


        wpa_cli scan_results > /tmp/EvnpinvAvpininZ8.tmp
        sed '1,2d' < /tmp/EvnpinvAvpininZ8.tmp | sed 's/.\{26\}//' | sed 's/.*]//' | sed '/^[[:space:]]*$/d' | sed 's/^[[:space:]]//' > /tmp/Ev2npinvAvpininZ8.tmp

        sleep 1

        echo 100

    } | dialog --gauge "Scan in progress..." 6 24 0

    # Nom du fichier contenant les SSID
    SSID_FILE="/tmp/Ev2npinvAvpininZ8.tmp"

    # Build the options array for the dialog box
    DIALOG_OPTS=""
    while read -r ssid; do
        DIALOG_OPTS="$DIALOG_OPTS ${ssid} ''"
    done < "$SSID_FILE"

    # Display the dialog box to choose the WiFi network
    chosen_ssid=$(dialog --backtitle "Detected WiFi Networks" --title "List" --menu "Choose a WiFi network:" 0 0 0 "$DIALOG_OPTS" 3>&1 1>&2 2>&3)

    ssid=$(grep "$chosen_ssid" < /tmp/EvnpinvAvpininZ8.tmp)

    # Check the security type
    check=$(echo "$ssid" | grep -o "PSK" | wc -l | tr -d ' ')

    if [ "$check" -gt 0 ]; then

        password=$(dialog --title 'Enter Password' --inputbox "Please enter the password" 8 35 2>&1 1>/dev/tty)

        {
            echo " "
            echo "network={"
            echo "  ssid=\"$chosen_ssid\""
            echo "  psk=\"$password\""
            echo "  proto=RSN"
            echo "  key_mgmt=WPA-PSK"
            echo "  pairwise=CCMP"
            echo "}"
        } >> /etc/wpa_supplicant.conf
    fi

    # Reload wpa_supplicant
    service wpa_supplicant reload > /dev/null 2>&1

    # Restart the dhcpd service
    service dhcpcd restart > /dev/null 2>&1

    # Remove configuration files:
    rm /tmp/EvnpinvAvpininZ8.tmp
    rm /tmp/Ev2npinvAvpininZ8.tmp



    NetworkMenu
}

# checked

SwitchToEthernet () {

    # Create a temporary file
    TMPFILE=$(mktemp)

    # Get NICs
    netstat -i | cut -d' ' -f1 | grep -v "Name" | grep -v "lo0" | grep -v "npflo" | tr -d '*' | sort | uniq > "$TMPFILE"

    # Check if the list is empty
    if [ ! -s "$TMPFILE" ]; then
        dialog --msgbox "No NIC detected" 5 30
        rm -f "$TMPFILE"
        NetworkMenu
    fi

    # Read the temporary file and construct the option for dialog
    devices=""
    while IFS= read -r line; do
        devices="$devices $line \"$line\" off"
    done < "$TMPFILE"

    # Use dialog to display the list of devices
    device=$(eval "dialog --radiolist \"Choose the Ethernet NIC please\" 0 0 0 $devices 3>&1 1>&2 2>&3")

    # Clean up and remove the temporary file
    rm -f "$TMPFILE"

    # choice of the user :
    #echo $device


    # Create a temporary file
    TMPFILE=$(mktemp)

    # Get NICs
    netstat -i | cut -d' ' -f1 | grep -v "Name" | grep -v "lo0" | grep -v "npflo" | tr -d '*' | sort | uniq > "$TMPFILE"

    # Check if the list is empty
    if [ ! -s "$TMPFILE" ]; then
        dialog --msgbox "No NIC detected" 5 30
        rm -f "$TMPFILE"
        NetworkMenu
    fi

    # Read the temporary file and construct the option for dialog
    devices=""
    while IFS= read -r line; do
        devices="$devices $line \"$line\" off"
    done < "$TMPFILE"

    # Use dialog to display the list of devices
    wifiNIC=$(eval "dialog --radiolist \"Choose the Wifi NIC please\" 0 0 0 $devices 3>&1 1>&2 2>&3")

    # Clean up and remove the temporary file
    rm -f "$TMPFILE"


    {

        # Stop the wpa_supplicant service:
        service wpa_supplicant stop > /dev/null 2>&1
        sleep 2
        # Disable wpa_supplicant at startup
        check=$(grep -o 'wpa_supplicant=' < /etc/rc.conf | sort | uniq | wc -l | tr -d ' ')
        if [ "$check" -eq 1 ]; then
            service wpa_supplicant stop > /dev/null 2>&1
            sed -i '/wpa_supplicant=YES/d' /etc/rc.conf
        fi

        echo 25

        # Turn off the wifi card:
        ifconfig "$wifiNIC" down > /dev/null 2>&1
        # Stop and Disable ${wifiNIC} at startup
        check=$(grep -o "ifconfig_${wifiNIC}=" < /etc/rc.conf | sort | uniq  | wc -l | tr -d ' ')
        if [ "$check" -eq 1 ]; then
            ifconfig "${wifiNIC}" down > /dev/null 2>&1
            sed -i "/ifconfig_${wifiNIC}=\"up\"/d" /etc/rc.conf
        fi
        sleep 2

        echo 50

        # Change the WAN interface in the firewall rules file:
        FILE="/etc/npf.conf"

        # Replace "${wifiNIC}" with "${device}" in specific lines
        if [ -f "$FILE" ]; then
            sed -i'' -e "/^\$WAN_if = \"${wifiNIC}\"/s/${wifiNIC}/${device}/" -e "/^\$WAN_addrs = ifaddrs(${wifiNIC})/s/${wifiNIC}/${device}/" "$FILE"
            # Restart the firewall
            service npf restart > /dev/null 2>&1
        fi

        echo 75

        # Remove the wifi card flags from dhcpcd_flags
        FILE="/etc/rc.conf"

        # Check if the dhcpcd_flags entry exists and contains "${wifiNIC}"
        if grep -q "^dhcpcd_flags=.*${wifiNIC}" "$FILE"; then
            # Use sed to remove "${wifiNIC}" from dhcpcd_flags
            sed -i'' -e "/^dhcpcd_flags=/s/ ${wifiNIC}//" "$FILE"
        fi

        # Restart dhcpcd
        service dhcpcd restart > /dev/null 2>&1

        echo 100


        } | dialog --gauge "Disabling Wifi..." 6 22 0


    dialog --msgbox "Wifi Disabled" 5 18

    NetworkMenu
}

# checked


getentPasswd () {
    # Display the contents of the /etc/passwd file in a dialog screen
    dialog --backtitle "Contents of the /etc/passwd file" --title "Users" --textbox /etc/passwd 0 0

    # Call UsersRightsMenu after dialog closes
    UsersRightsMenu
}

# checked


CreateUser () {
    # Dialog to get the username
    user=$(dialog --title '   Create a User' --inputbox "Please enter the username" 8 43 2>&1 1>/dev/tty)

    # Verification:
    countus=$(getent passwd "$user" | cut -d: -f1)
    case $countus in
        "$user")
            dialog --backtitle "User Exists!" \
                   --title '   Result' \
                   --msgbox "The user exists" 5 24
            UsersRightsMenu
        ;;
    esac

    # Dialog to ask if a home directory should be created
    dialog --yesno "Do you want to create a home directory for the user" 5 56
    create_home=$?

    if [ "$create_home" -eq 0 ]; then
    dialog --yesno "/home/$user ?" 5 50
    homestandard=$?

        if [ "$homestandard" -eq 1 ]; then
            perso=$(dialog --title "Custom Location" --inputbox "Please enter the absolute path of the desired base directory. (example: /export/home/$user)" 9 70 2>&1 1>/dev/tty)
            mkdir -p "${perso}"
            useradd_options="-md ${perso}"

        fi

        if [ "$homestandard" -eq 0 ]; then

            useradd_options="-md /home/$user"

        fi
    fi


    # Dialog to ask if the user should be allowed to log in
    dialog --yesno "Do you want to allow login on this system" 5 46
    login_shell=$?

    # Dialog to ask for the maximum password validity period
    password_expire=$(dialog --title "Password Expiration" --inputbox "Please enter the maximum password validity period (in days)" 9 64 2>&1 1>/dev/tty)

    # Dialog to ask for the groups the user should be added to
    groups=$(dialog --title "User Groups" --inputbox "Please enter the groups separated by commas to which the user should be added" 9 70 2>&1 1>/dev/tty)
    pass=$(dialog --title "Password" --inputbox "Please enter a password" 8 30 2>&1 1>/dev/tty)

    dialog --yesno "Do you want to allow the user to change password on first login?" 6 68
    changeAtlogon=$?

    # Creating the options string:

    if [ "$login_shell" -eq 1 ]; then
        useradd_options="${useradd_options} -s /sbin/nologin" # Disable login if not allowed
    fi
    if [ "$password_expire" ]; then
        useradd_options="${useradd_options} -f $password_expire" # Maximum password validity period
    fi

    # Adding the user to the specified groups
    count=$(echo "$groups" | grep -o ',' | wc -c | tr -d ' ')

    if [ "$count" -eq 0 ]; then
        useradd_options="${useradd_options} -G $groups"
    fi

    i=1
    while [ $i -le "$count" ]; do

        grouptoadd=$(echo "$groups" | cut -d',' -f$i)
        useradd_options="${useradd_options} -G $grouptoadd"
        i=$((i+1))

    done

    if [ "$pass" ]; then
        useradd_options="${useradd_options} -p ${pass}"
    fi

    if [ "$changeAtlogon" -eq 0 ]; then
        useradd_options="${useradd_options} -F"
    fi


    # Creating the user with the chosen options
    useradd "$useradd_options" "$user"
    passwd "${user}"

    dialog --backtitle "User Created!" \
           --title '   Result' \
           --msgbox "The user has been successfully created" 5 42

    UsersRightsMenu

}

# checked

DeleteUser () {
    # Get the list of system users excluding specified users
    users=$(getent passwd | cut -d: -f1 | grep -Ev 'root|toor|daemon|operator|wheel|bin|games|postfix|named|ntpd|sshd|_pflogd|_proxy|_timedc|_sdpd|_httpd|_mdnsd|_rwhod|_tests|_tcpdump|_tss|_rtadvd|_unbound|_nsd|_dhcpcd|uucp|nobody|dbus|polkitd')

    # Check if the list of users is empty
    if [ -z "$users" ]; then
        dialog --backtitle "Remove a User" \
               --title "No Users Available" \
               --msgbox "No users to remove." 8 50
        return
    fi

    # Initialize an empty string to store dialog options
    dialog_options=""

    # Loop through the list of users
    for user in $users; do
        # Get the user's ID
        uid=$(id -u "$user")

        # Check if the user's ID was successfully retrieved
        if [ -z "$uid" ]; then
            echo "Error: Unable to find user ID for $user"
            continue
        fi

        # Build each option and add it to the dialog options string
        dialog_options="$dialog_options $user $uid off"
    done



    # Display the checkbox dialog to select users for deletion
    selected_users=$(dialog --backtitle "Remove a User" \
                             --title "Choose whom to remove" \
                             --checklist "Use space bar. Choose only one user if you want to archive the home folder. To remove all, select as many users as necessary:" \
                             20 60 10 \
                             "$dialog_options" \
                             2>&1 >/dev/tty)

    # Check if users have been selected
    if [ -n "$selected_users" ]; then
        # Ask if the home directory should also be removed
        dialog --yesno "Do you also want to remove the home directory of the selected user?" 6 65
        remove_home=$?

        # Remove the selected users
        for user in $selected_users; do
            if [ $remove_home -eq 0 ]; then
                # Remove the user and their home directory
                userdel -r "$user"
            else
                dialog --yesno "Do you want to archive the home directory of the selected user?" 6 65
                compress_home=$?

                if [ $compress_home -eq 0 ]; then
                    # Get the user's home directory
                    user_home=$(getent passwd "$user" | cut -d: -f6)

                    # Check if the directory exists
                    if [ -d "$user_home" ]; then
                        # Archive and compress the directory
                        tar cf - "$user_home" | xz > "${user_home}.tar.xz"
                        userdel -r "$user"
                    else
                        dialog --backtitle "Directory Not Found!" \
                               --title 'Directory Not Found' \
                               --msgbox "The home directory does not exist." 5 38
                    fi
                else
                    userdel "$user"
                fi
            fi
        done
    fi



        dialog --backtitle "User(s) Removed!" \
               --title '   Result' \
               --msgbox "Deletion Successful" 5 23


    UsersRightsMenu
}

# checked

getentGroup () {
    # Display the contents of the /etc/group file in a dialog box
    dialog --backtitle "Contents of /etc/group file" --title "Groups" --textbox /etc/group 0 0

    # Call UsersRightsMenu after dialog is closed
    UsersRightsMenu
}

# checked



CreateGroup () {

    groupName=$(dialog --title "   Add a Group" --inputbox "Please enter the group name" 8 34 2>&1 1>/dev/tty)
    countus=$(getent group "$groupName" | cut -d: -f1)
    case $countus in
        "$groupName")
            dialog  --backtitle "Group Exists!" \
                    --title " Result" \
                    --msgbox "Group Exists" 5 17
        ;;
        *)
            groupadd "$groupName" 2>/dev/null

            countus2=$(getent group "$groupName" | cut -d: -f1)
            case $countus2 in
                "$groupName")
                    dialog  --backtitle "Group Created" \
                            --title " Result" \
                            --msgbox "The group has been successfully created" 5 43
                ;;
                *)
                    dialog  --backtitle "Error" \
                            --title " Result" \
                            --msgbox "Error creating the group" 5 29
            esac
        ;;
    esac

    UsersRightsMenu

}


CheckGroupExists () {

    groupName=$(dialog --title " Check Group Existence" --inputbox "Please enter the group name" 8 37 2>&1 1>/dev/tty)
    countus=$(getent group "$groupName" | cut -d: -f1)
    case $countus in
        "$groupName")
            dialog  --backtitle "Group Exists!" \
                    --title " Result" \
                    --msgbox "Group Exists" 5 17
        ;;
        *)
            dialog  --backtitle "Group Not Found!" \
                    --title "  Result" \
                    --msgbox "Group Not Found" 5 20

        ;;
    esac

    UsersRightsMenu

}

# checked


DeleteGroup () {

    groupName=$(dialog --title " Delete a group" --inputbox "Please enter the group name" 8 37 2>&1 1>/dev/tty)
    countus=$(getent group "$groupName" | cut -d: -f1)
    case $countus in
        "$groupName")

            groupdel "$groupName" 2>/dev/null

            countus=$(getent group "$groupName" | cut -d: -f1)
            case $countus in
                "$groupName")
                    dialog  --backtitle "Error!" \
                            --title " Result" \
                            --msgbox "Group not deleted" 5 21
                ;;
                *)
                    dialog  --backtitle "Group Deleted!" \
                            --title " Result" \
                            --msgbox "Group Deleted" 5 17
                ;;
            esac


        ;;
        *)
            dialog  --backtitle "Group Not Found!" \
                    --title "  Result" \
                    --msgbox "Group Not Found" 5 19

        ;;
    esac

    UsersRightsMenu

}


AddToGroup () {

    # Dialogue to get the username
    user=$(dialog --title "Check User Existence" --inputbox "Please enter the username" 8 30 2>&1 1>/dev/tty)
    countus=$(getent passwd "$user" | cut -d: -f1)

    case $countus in
        "$user")
            group=$(dialog --title "Check Group Existence" --inputbox "Please enter the group name" 8 32 2>&1 1>/dev/tty)
            countus2=$(getent group "$group" | cut -d: -f1)

            case $countus2 in
                "$group")
                        usermod -G "$group" "$user"
                        countus3=$(groups "$user" | grep -o "$group")

                        case $countus3 in
                            "$group")
                                dialog  --backtitle "User Added" \
                                        --title '   Result' \
                                        --msgbox "User added" 5 15
                            ;;
                            *)
                                dialog  --backtitle "Error" \
                                        --title '   Result' \
                                        --msgbox "User not added" 5 19

                                        UsersRightMenu
                            ;;
                        esac

                ;;
                *)
                    dialog  --backtitle "Group Not Found!" \
                            --title '   Result' \
                            --msgbox "The group does not exist" 5 29

                    UsersRightsMenu
                ;;
            esac

        ;;
        *)
            dialog --backtitle "User Not Found!" \
                   --title '   Result' \
                   --msgbox "The user does not exist" 5 28

                   UsersRightsMenu
        ;;
    esac

    UsersRightsMenu
}

# checked


LeaveGroup () {

    dialog  --backtitle "Modify /etc/group" \
            --title '   Modify /etc/group' \
            --msgbox "The /etc/group file will open. Please locate the line starting with the group name, then remove your username and any extra comma, then exit (ctrl+x) and save (Y) in /etc/group" 7 70
    pico /etc/group

    UsersRightsMenu

}

# checked


ovpnVPN () {
    checkInternetConnection

    openVPNinstallation () {
        clear
        echo "--------------------------------------------------"
        echo "Installation in progress, please wait ..."
        echo " "

        pkgin -y in wget 
        pkgin -y in curl 
        pkgin -y in openvpn 
        pkgin -y in unzip

        clear
        echo "--------------------------------------------------"
        echo "Do you want to require the server to connect to the VPN upon startup? [y],"
        echo "Or do you prefer to decide when to connect it yourself? [n]"
        read -r ansou
        case $ansou in
            y|Y)
                echo openvpn=YES
            ;;
            n|N)

            ;;
        esac

    }

    startovpnconnection () {

        clear
        echo "--------------------------------------------------"
        echo "Connection is starting, please wait..."
        openvpn --config /usr/pkg/etc/openvpn/ovpn.conf --daemon
        sleep 10
        echo " "
        echo "--------------------------------------------------"
        echo "Do you want to check if the connection was successful ? [y/n]"
        read -r ansverif
        case $ansverif in
            y|Y)
                echo " "
                echo "--------------------------------------------------"
                echo "if success:true happens, you're connected:"
                echo " "
                curl https://www.ovpn.com/v2/api/client/ptr
                sleep 5
                return
            ;;
            n|N)

            ;;
        esac

    }

    addOVPNcredentials () {
        echo ""
        echo "--------------------------------------------------"
        echo "Please enter your OVPN login:"
        read -r nameu
        echo "$nameu" >> /usr/pkg/etc/openvpn/credentials
        echo ""
        echo "--------------------------------------------------"
        echo "Please enter your OVPN password:"
        read -r mtpu
        echo "$mtpu" >> /usr/pkg/etc/openvpn/credentials

    }

    OVPNconfiguration () {
        # All the OVPN servers around the world
        places="at-vienna at-vienna-tcp au-sydney au-sidney-tcp ca-toronto ca-toronto-tcp dk-copenhagen dk-copenhagen-tcp fi-helsinki fi-helsinki-tcp fr-paris fr-paris-tcp de-erfurt de-erfurt-tcp de-frankfurt de-frankfurt-tcp de-offenbach de-offenbach-tcp it-milan it-milan-tcp jp-tokyo jp-tokyo-tcp nl-amsterdam nl-amsterdam-tcp no-oslo no-oslo-tcp pl-warsaw pl-warsaw-tcp ro-bucharest ro-bucharest-tcp sg-singapore sg-singapore-tcp es-madrid es-madrid-tcp se-gothenburg se-gothenburg-tcp se-malmo se-malmo-tcp se-stockholm se-stockholm-tcp se-sundsvall se-sundsvall-tcp ch-zurich ch-zurich-tcp gb-london gb-london-tcp us-atlanta us-atlanta-tcp us-chicago us-chicago-tcp us-dallas us-dallas-tcp us-denver us-denver-tcp us-losangeles us-losangeles-tcp us-miami us-miami-tcp us-newyork us-newyork-tcp us-seattle us-seattle-tcp ua-kyiv ua-kyiv-tcp"

        clear
        echo "---------------------------------------"
        echo "# Here is the list of available places"
        echo "# (tcp not written = udp)"
        echo ""

        i=1
        for place in $places; do
            echo "$i - $place"
            i=$((i + 1))
        done

        echo ""
        echo "Please choose a place by its number:"
        read -r choice

        i=1
        for place in $places; do
            if [ "$i" -eq "$choice" ]; then

                # Download file configuration from ovpn and install it
                wget https://files.ovpn.com/freebsd/ovpn-"${place}".zip -P /tmp
                #cd /tmp ; unzip ovpn-"${place}".zip
                unzip /tmp/ovpn-"${place}".zip -d /tmp/
                rm -r /usr/pkg/etc/openvpn
                mkdir -p /usr/pkg/etc/openvpn
                touch /usr/pkg/etc/openvpn/update-resolv-conf
                mv /tmp/config/* /usr/pkg/etc/openvpn/
                chmod +x /usr/pkg/etc/openvpn/update-resolv-conf
                rm -rf /tmp/config
                rm -f /tmp/ovpn-"${place}".zip

                # Adapt file configuration to NetBSD
                sed -i'' "s/\/usr\/local/\/usr\/pkg/" /usr/pkg/etc/openvpn/ovpn.conf
                sleep 1
                sed -i "/^log/d" /usr/pkg/etc/openvpn/ovpn.conf
                sleep 1
                echo "" >> /usr/pkg/etc/openvpn/ovpn.conf
                echo "log /var/log/openvpn.log" >> /usr/pkg/etc/openvpn/ovpn.conf

                # Add OVPN credentials
                addOVPNcredentials

                # Start OVPN or not
                clear
                echo "--------------------------------------------------"
                echo "Do you want to connect to OVPN now ? [y/n]"
                read -r answno
                case $answno in
                    y|Y)
                        startovpnconnection
                    ;;
                    n|N)
                    ;;
                esac

            fi
            i=$((i + 1))
        done
    }


    i=0
    while [ $i -lt 5 ]; do
        clear
        echo "--------------------------------------------------"
        echo "What do you want to do ?"
        echo ""
        echo " - connect to the VPN [c],"
        echo " - disconnect from the VPN [d],"
        echo " - proceed with the configuration? [p]"
        echo ""
        echo "--------------------------------------------------"
        echo "Please enter the letter:"
        read -r cinst
        case $cinst in
            c|C)
                startovpnconnection
                i=$((i+6))
            ;;
            d|D)
                pkill openvpn
                i=$((i+6))
            ;;
            p|P)
                openVPNinstallation
                OVPNconfiguration
                i=$((i+6))
            ;;
            *)
                echo "--------------------------------------------------"
                echo "I didn't understand your choice."
                echo "Please enter only c/d/p"
                sleep 3
                i=$((i+1))
            ;;
        esac
    done

    MainMenu
}


installClamAV () {

    checkInternetConnection

    {

        pkgin -y in clamav clamav-doc
        pkgin -y in rsync
        cp /usr/pkg/share/examples/rc.d/* /etc/rc.d/

        check=$(grep -o "freshclamd=YES" < /etc/rc.conf | wc -l | tr -d ' ' )
        if [ "$check" -eq 0 ]; then
            echo freshclamd=YES >> /etc/rc.conf
        fi

        service freshclamd start > /dev/null 2>&1

        mkdir -p /var/db/clamav/quarantine > /dev/null 2>&1
        chown clamav:clamav /var/db/clamav/quarantine > /dev/null 2>&1


        ############
        # Optimize threat detection configuration:

        # Remove settings from previous installation:
        FILE="/usr/pkg/etc/clamd.conf"
        PATTERN="# OPTIMIZED CONFIGURATION"

        # Check if file and string exist
        if [ -f "$FILE" ] && grep -q "$PATTERN" "$FILE"; then
            # Remove all lines from the string onwards
            sed -i'' "/$PATTERN/,\$d" "$FILE"
        fi
        {
            echo " "
            echo "# OPTIMIZED CONFIGURATION"
            echo "DetectPUA yes"
            echo "ExcludePUA PUA.Win.Packer"
            echo "ExcludePUA PUA.Win.Trojan.Packed"
            echo "ExcludePUA PUA.Win.Packer.Upx"
            echo "ExcludePUA PUA.Doc.Packed"
            echo "MaxScanTime 120000"
            echo "MaxScanSize 20480M"
            echo "MaxRecursion 30"
            echo "MaxFiles 15000"
            echo "MaxEmbeddedPE 2048M"
            echo "MaxHTMLNormalize 2048M"
            echo "MaxHTMLNoTags 2048M"
            echo "MaxScriptNormalize 2048M"
            echo "MaxZipTypeRcg 50M"
            echo "PCREMaxFileSize 2048M"
        } >> /usr/pkg/etc/clamd.conf

    } | dialog --gauge "Installation and optimization in progress..." 6 50 0


    dialog --yesno "Would you like to set up the security bases from securiteinfo.com? You must have a paid subscription. Please create a file /tmp/dbsecuriteinfo.tmp containing the blocks 'DatabaseCustomURL https://...' provided in your customer area on the securiteinfo.com website, or copy/paste them into the text file that will open during verification. You can rerun the ClamAV installation script later to add your URLs when you have them" 12 65
    create_securinfo=$?

    if [ $create_securinfo -eq 0 ]; then

        # Add the securiteinfo.com download URLs to freshclam
        # Remove settings from a previous installation:
        FILE="/usr/pkg/etc/freshclam.conf"
        PATTERN="# SECURITEINFO.COM BASES"

        # Check if the file and string exist
        if [ -f "$FILE" ] && grep -q "$PATTERN" "$FILE"; then
            # Remove all lines from the string onwards
            sed -i'' "/$PATTERN/,\$d" "$FILE"
        fi

        dialog --msgbox "The text file will open, please make sure to place one 'DatabaseCustomUrl https://...' group per line.\nThen exit and save without changing the file location" 7 60
        pico /tmp/dbsecuriteinfo.tmp
        {
            echo ""
            echo "# SECURITEINFO.COM BASES"
        } >> /usr/pkg/etc/freshclam.conf

        cat /tmp/dbsecuriteinfo.tmp >> /usr/pkg/etc/freshclam.conf

        service freshclamd restart > /dev/null 2>&1
        freshclam > /dev/null 2>&1

    fi

    dialog --yesno "Would you like to set up the security bases from SaneSecurity?" 5 67
    create_sanesecu=$?

    if [ $create_sanesecu -eq 0 ]; then

        # Direct download of the bases
        if [ ! -e /usr/pkg/bin/rsync ]; then
            pkgin -y in rsync
        fi

        rsync rsync://rsync.sanesecurity.net/sanesecurity/* /var/clamav/ > /dev/null 2>&1

    fi

    dialog --msgbox "Installation Completed" 5 27


    AntiVirusMenu

}

UpdateSaneSecurityClamAV () {

    checkInternetConnection

    {
        nohup rsync rsync://rsync.sanesecurity.net/sanesecurity/* /var/clamav/ &

        echo 100

    } | dialog --gauge "Update in progress..." 6 30 0

    AntiVirusMenu

}

FullScanClamAV () {

    dialog --msgbox "Scanning / will begin..." 5 30
    dialog --msgbox "The log will be located in /var/db/clamav/scan.log" 6 32

    nohup clamscan -r --log=/var/db/clamav/scan.log --move=/var/db/clamav/quarantine / &

    dialog --msgbox "Scan launched in the background" 5 35

    AntiVirusMenu
}

HomeScanClamAV () {

    dialog --msgbox "Scanning /home will begin..." 5 33
    dialog --msgbox "The log will be located in /var/db/clamav/scan.log" 6 32

    nohup clamscan -r --log=/var/db/clamav/scan.log --move=/var/db/clamav/quarantine /home &

    dialog --msgbox "Scan launched in the background" 5 35

    AntiVirusMenu
}


LogClamAV () {

    dialog --textbox /var/db/clamav/scan.log 0 0

    AntiVirusMenu

}

ArchiveLogClamAV () {

    # Get the date and time in the desired format
    DATE=$(date "+%d-%m-%Y")
    TIME=$(date "+%H:%M:%S")

    # Path of the file to compress
    FILE="/var/db/clamav/scan.log"

    # Check if the file to compress exists
    if [ ! -f "$FILE" ]; then
        dialog --msgbox "The file to compress does not exist" 5 40
        AntiVirusMenu
    fi

    # Compressed file name
    COMPRESSED_FILE_NAME="scan_${DATE}_${TIME}.xz"

    # Full path of the compressed file
    COMPRESSED_FILE_PATH="/var/db/clamav/${COMPRESSED_FILE_NAME}"

    # Compress the file
    xz "$FILE" -c > "$COMPRESSED_FILE_PATH"

    AntiVirusMenu
}


CleanLogClamAV () {

    dialog --yesno "Are you sure you want to delete the log?" 5 45
    confirm=$?

    if [ "$confirm" -eq 0 ]; then
        rm /var/db/clamav/scan.log
        touch /var/db/clamav/scan.log
    fi

    AntiVirusMenu
}

locateRebuild () {

    {

        /usr/libexec/locate.updatedb

        echo 100

    } | dialog --gauge "Rebuilding index..." 6 40 0

    dialog --msgbox "Rebuilding complete" 5 23

    MainMenu
}


CheckUserExists () {

    # Dialogue to get the username
    user=$(dialog --title "Check User Existence" --inputbox "Please enter the username" 8 30 2>&1 1>/dev/tty)
    countus=$(getent passwd "$user" | cut -d: -f1)

    case $countus in
        "$user")
            userInfo=$(id "$user")
            dialog --backtitle "User Exists!" \
                   --title '  Result' \
                   --msgbox "The user exists:\n\nInformation:\n$userInfo" 10 50
        ;;
        *)
            dialog --backtitle "User Not Found!" \
                   --title '   Result' \
                   --msgbox "The user does not exist" 5 28
        ;;
    esac

    UsersRightsMenu

}

SFTPFS () {

    # Check if OpenSSH is installed or not
    check=$(grep -o "sshd=YES" < /etc/rc.conf | wc -l | tr -d ' ')
    if [ "$check" -eq 0 ]; then

        if [ ! -e /usr/sbin/sshd ]; then

            dialog --yesno "OpenSSH is not installed on your system, do you want to install it?" 6 44
            sshd_install=$?

            checkInternetConnection

            if [ "$sshd_install" -eq 0 ]; then

                pkgin -y in opensshd
                # I don't remember if sshd goes automatically to /etc/rc.d/... in case :
                cp /usr/pkg/share/examples/rc.d/sshd /etc/rc.d/sshd

                echo sshd=YES >> /etc/rc.conf

            fi

        else

            echo sshd=YES >> /etc/rc.conf

        fi

    fi

    # check if a previous SFTP file server is already configured
    check22=$(grep -o "sftpexclusive" < /etc/ssh/sshd_config | sort | uniq | wc -l | tr -d ' ')

    if [ "$check22" -eq "1" ]; then

        dialog --msgbox "This server is already configured as SFTP File Server" 5 57
        ServicesMenu

    fi


    # Check if /etc/ssh/sshd_config contains Subsystem sftp command
    check=$(grep Subsystem < /etc/ssh/sshd_config | grep sftp | sort | uniq | wc -l | tr -d ' ')
    if [ "$check" -eq 1 ]; then

        # now, check if the sftp is internal-sftp
        check2=$(grep Subsystem < /etc/ssh/sshd_config | grep "internal-sftp" | sort | uniq | wc -l | tr -d ' ')
        if [ "$check2" -eq 0 ]; then

            # Configure sftp-internal + nosftp + sftpexclusive group and user chrooting to /SFTP/%u
            #sed -i'' "s/\/usr\/libexec\/sftp-server/internal-sftp\n\nMatch Group sftpexclusive\n     ChrootDirectory \/SFTP\/%u\n     ForceCommand internal-sftp\n     AllowTcpForwarding no\n     X11Forwarding no\n/" /etc/ssh/sshd_config
            sed -i'' "s/\/usr\/libexec\/sftp-server/internal-sftp\n\nMatch Group nosftp\n     ForceCommand \/usr\/bin\/false\n\nMatch Group sftpexclusive\n     ChrootDirectory \/SFTP\/%u\n     ForceCommand internal-sftp\n     AllowTcpForwarding no\n     X11Forwarding no\n/" /etc/ssh/sshd_config

        fi

    else

        # Add a Subystem + configuration
        {
            echo " "
            echo "# SFTP FILE SERVER"
            echo "Subsystem       sftp    internal-sftp"
            echo " "
            echo "Match group nosftp"
            echo "     ForceCommand /usr/bin/false"
            echo " "
            echo "Match Group sftpexclusive"
            echo "     ChrootDirectory /SFTP/%u"
            echo "     ForceCommand internal-sftp"
            echo "     AllowTcpForwarding no"
            echo "     X11Forwarding no"
            echo " "
        } >> /etc/ssh/sshd_config

    fi

    # Create groups nosftp and sftpexclusive
    groupadd nosftp 2>/dev/null
    groupadd sftpexclusive 2>/dev/null

    # Add the /usr/bin/false shell to /etc/shells (in order to deactivate user account in case)
    echo "/usr/bin/false" >> /etc/shells

    # deactivate Motd
    check4=$(grep -o '#PrintMotd yes' < /etc/ssh/sshd_config | wc -l | tr -d ' ')
    if [ "$check4" -eq 1 ]; then

        sed -i'' "s/#PrintMotd yes/PrintMotd no/" /etc/ssh/sshd_config

    fi
    check41=$(grep -o 'PrintMotd yes' < /etc/ssh/sshd_config | wc -l | tr -d ' ')
    if [ "$check41" -eq 1 ]; then

        sed -i'' "s/PrintMotd yes/PrintMotd no/" /etc/ssh/sshd_config

    fi



    # deactivate Banner
    check5=$(grep -o '#Banner none' < /etc/ssh/sshd_config | wc -l | tr -d ' ')
    if [ "$check5" -eq 1 ]; then

        sed -i'' "s/#Banner none/Banner none/" /etc/ssh/sshd_config

    fi
    check51=$(grep -o 'Banner none' < /etc/ssh/sshd_config | wc -l | tr -d ' ')
    if [ "$check51" -eq 1 ]; then

        sed -i'' "s/Banner none/Banner none/" /etc/ssh/sshd_config

    fi

    # Restart SSH
    service sshd restart  > /dev/null 2>&1



    # check if the NPF firewall has already been configured.
    i=0
    while [ $i -lt "3" ]; do
        if [ -e /etc/npf.conf ]; then

            # check if NPF is active
            check=$(npfctl show | grep -o "inactive" | sort | uniq | wc -l | tr -d ' ')
            if [ ! "$check" -eq 1 ]; then

                # NPF is active
                # check SSH port is the same than in /etc/npf.conf
                sshdport=$(grep 'Port ' < /etc/ssh/sshd_config | grep -o "[0-9]" | tr -d "\n")


                npfsshport=$(grep ssh < /etc/npf.conf | grep -o ssh | sort | uniq | wc -l | tr -d ' ')
                if [ "$npfsshport" -eq 1 ]; then

                    npfsshport="22"


                fi
                npfsshport2=$(grep ssh < /etc/npf.conf | grep -o "22" | sort | uniq | wc -l | tr -d ' ')
                if [ "$npfsshport2" -eq 1 ]; then

                    npfsshport="22"

                fi

                # Compare the 2 var
                if [ "$sshdport" -eq "$npfsshport" ]; then
                    # perfect ! Same port
                    i=$((i+11))
                else
                    # SSH ports are different between /etc/ssh/sshd_config and /etc/npf.conf
                    dialog --msgbox "The NPF firewall seems to be active but the SSH port is different between /etc/ssh/sshd_config and /etc/npf.conf\n\n/etc/ssh/sshd_config and then /etc/npf.conf will open so that you can make your changes" 9 70
                    pico /etc/ssh/sshd_config
                    pico /etc/npf.conf

                    service npf restart > /dev/null 2>&1
                    service sshd restart  > /dev/null 2>&1
                fi

            else

                dialog --yesno "The NPF firewall seems inactive\nWould you like to configure it?" 6 35
                npf_ornot=$?

                if [ "$npf_ornot" -eq 0 ]; then

                    PareFeu

                fi


            fi


        else

                dialog --yesno "The NPF firewall seems inactive\nWould you like to configure it?" 6 35
                npf_ornot=$?

                if [ "$npf_ornot" -eq 0 ]; then

                    PareFeu

                fi


        fi

        i=$((i+1))
    done


    dialog --msgbox "The configuration is done!\nPlease now create SFTP users" 6 32

}

CreateSFTPuser () {


    # check if a previous SFTP file server is already configured
    check22=$(grep -o "sftpexclusive" < /etc/ssh/sshd_config | sort | uniq | wc -l | tr -d ' ')

    if [ ! "$check22" -eq "1" ]; then

        dialog --msgbox "This server is not configured as SFTP File Server\nPlease 'Configure a SFTP file server with OpenSSH'" 6 54
        OpenSSHFSMenu

    fi

    # Get the username to create
    user=$(dialog --title "Adding a SFTP user" --inputbox "Please enter the username of the new SFTP user" 8 52 2>&1 1>/dev/tty)

    # check if the user already exists
    countus=$(getent passwd "$user" | cut -d: -f1)
    case $countus in
        "$user")
            dialog --msgbox "This user already exists" 5 29
            OpenSSHFSMenu

        ;;
        *)
        ;;
    esac

    # Create the user with no login access and a home directory to /SFTP/user
    useradd -G sftpexclusive -s /sbin/nologin -m -d /SFTP/"${user}" "${user}"

    passwd "${user}"

    # Permissions :
    /sbin/chown root:sftpexclusive /SFTP/"${user}"
    chmod 755 /SFTP/"${user}"


    # Check if everything has been done correctly
    countus=$(getent passwd "$user" | cut -d: -f1 | wc -l | tr -d ' ')
    if [ "$countus" -eq 1 ]; then

        if [ -d /SFTP/"${user}" ]; then
            dialog --msgbox "${user} has been correctly created and is member of sftpexclusive" 6 70
        else
            dialog --msgbox "Something went wrong" 5 24
        fi


    fi

OpenSSHFSMenu
}

DeleteSFTPuser () {
    # Get the list of system users excluding specified users
    users=$(getent passwd | grep '/SFTP/' | cut -d: -f1)

    # Check if the list of users is empty
    if [ -z "$users" ]; then
        dialog --backtitle "Remove a User" \
               --title "No Users Available" \
               --msgbox "No users to remove." 8 50
        return
    fi

    # Initialize an empty string to store dialog options
    dialog_options=""

    # Loop through the list of users
    for user in $users; do
        # Get the user's ID
        uid=$(id -u "$user")

        # Check if the user's ID was successfully retrieved
        if [ -z "$uid" ]; then
            echo "Error: Unable to find user ID for $user"
            OpenSSHFSMenu
        fi

        # Build each option and add it to the dialog options string
        dialog_options="$dialog_options $user $uid off"
    done



    # Display the checkbox dialog to select users for deletion
    selected_users=$(dialog --backtitle "Remove a User" \
                             --title "Choose whom to remove" \
                             --checklist "Use space bar. Choose only one user if you want to archive the home folder. To remove all, select as many users as necessary:" \
                             20 60 10 \
                             "$dialog_options" \
                             2>&1 >/dev/tty)

    # Check if users have been selected
    if [ -n "$selected_users" ]; then
        # Ask if the home directory should also be removed
        dialog --yesno "Do you also want to remove the home directory of the selected user?" 6 65
        remove_home=$?

        # Remove the selected users
        for user in $selected_users; do
            if [ "$remove_home" -eq 0 ]; then
                # Remove the user and their home directory
                userdel -r "$user"
            else
                dialog --yesno "Do you want to archive the home directory of the selected user?" 6 65
                compress_home=$?

                if [ "$compress_home" -eq 0 ]; then
                    # Get the user's home directory
                    user_home="/SFTP/${user}"

                    # Check if the directory exists
                    if [ -d "$user_home" ]; then
                        # Archive and compress the directory
                        tar cf - "$user_home" | xz > "${user_home}.tar.xz"
                        userdel -r "$user"

                        dialog --msgbox "The home directory has been archived to /SFTP/${user}.tar.xz" 6 70
                    else
                        dialog --backtitle "Directory Not Found!" \
                               --title 'Directory Not Found' \
                               --msgbox "The home directory does not exist." 5 38
                    fi
                else
                    userdel "$user"
                fi
            fi
        done
    fi



        dialog --backtitle "User(s) Removed!" \
               --title '   Result' \
               --msgbox "Deletion Successful" 5 23


OpenSSHFSMenu
}

ListSFTPusers () {

    getent passwd | grep '/SFTP' | cut -d: -f1 > /tmp/AAervinrinZbiznvinzdmin32.tmp
    # Display the contents of the /etc/passwd file in a dialog screen
    dialog --backtitle "List of SFTP users" --title "SFTP" --textbox /tmp/AAervinrinZbiznvinzdmin32.tmp 0 0

    rm /tmp/AAervinrinZbiznvinzdmin32.tmp

    # Call OpenSSHFSMenu after dialog close
    OpenSSHFSMenu
}

ChangepassSFTPuser () {

    # Get the username
    user=$(dialog --title "Username" --inputbox "Please enter the username" 8 30 2>&1 1>/dev/tty)

    # check if the user already exists
    countus=$(getent passwd "$user" | cut -d: -f1)
    case $countus in
        "$user")
            passwd "${user}"
        ;;
        *)
            dialog --msgbox "User doesn't exist!" 5 23
            OpenSSHFSMenu
        ;;
    esac

OpenSSHFSMenu
}

DisableSFTPuser () {

    # Get the username
    user=$(dialog --title "Username" --inputbox "Please enter the username" 8 30 2>&1 1>/dev/tty)

    # check if the user already exists
    countus=$(getent passwd "$user" | cut -d: -f1)
    case $countus in
        "$user")
            usermod -G nosftp "${user}"
            countus3=$(groups "${user}" | grep -o "nosftp")

            case $countus3 in
                "nosftp")
                    dialog  --backtitle "User account disabled" \
                            --title '   Result' \
                            --msgbox "User account disabled" 5 25
                ;;
                *)
                    dialog  --backtitle "Error" \
                            --title '   Result' \
                            --msgbox "User not disabled" 5 25

                    OpenSSHFSMenu
                ;;
            esac
        ;;
        *)
            dialog --msgbox "User doesn't exist!" 5 23
            OpenSSHFSMenu
        ;;
    esac

OpenSSHFSMenu
}

ListDisabledSFTPusers () {

    grep '^nosftp:' /etc/group | cut -d: -f4 | tr ',' '\n' > /tmp/AAervinrinZbiznvinzdmin32.tmp
    # Display the contents of the /etc/passwd file in a dialog screen
    dialog --backtitle "List of SFTP disabled users" --title "DISABLED" --textbox /tmp/AAervinrinZbiznvinzdmin32.tmp 0 0

    rm /tmp/AAervinrinZbiznvinzdmin32.tmp

    # Call OpenSSHFSMenu after dialog close
    OpenSSHFSMenu

}

RenableSFTPuser () {

    # Get the username
    user=$(dialog --title "Username" --inputbox "Please enter the username" 8 30 2>&1 1>/dev/tty)

    # check if the user already exists
    countus=$(getent passwd "$user" | cut -d: -f1)
    case $countus in
        "$user")
            sed -i'' -e "/^nosftp:/s/,${user}\(,\|$\)/\1/" -e "/^nosftp:/s/${user},//" -e "/^nosftp:/s/,${user}$//" -e "/^nosftp:/s/:${user}$/:/" /etc/group

            countus3=$(groups "${user}" | grep -o nosftp)
            case $countus3 in
                "nosftp")
                    dialog  --backtitle "Error" \
                            --title '   Result' \
                            --msgbox "User not enabled" 5 25

                    OpenSSHFSMenu
                ;;
                *)
                    dialog  --backtitle "Enabled" \
                            --title '   Result' \
                            --msgbox "User account enabled" 5 25


                ;;
            esac
        ;;
        *)


        ;;
    esac

OpenSSHFSMenu

}

Fail2banStatus () {

    service fail2ban status > /tmp/aaevpinpaeinEAB.tmp

    dialog --title "Fail2ban Status" --textbox /tmp/aaevpinpaeinEAB.tmp 20 70

    rm /tmp/aaevpinpaeinEAB.tmp

    Fail2banMenu

}

ShowBannedIP () {

    fail2ban-client banned > /tmp/aaevpinpaeinEAB.tmp

    dialog --title "Fail2ban Banned IP" --textbox /tmp/aaevpinpaeinEAB.tmp 20 70

    rm /tmp/aaevpinpaeinEAB.tmp

    Fail2banMenu

}

UnbanAnIP () {

    # Create a temporary file
    TMPFILE=$(mktemp)

    # Get NICs
    fail2ban-client banned | grep -Eo '\b([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}\b|\b([0-9]{1,3}\.){3}[0-9]{1,3}\b' > "$TMPFILE"

    # Check if the list is empty
    if [ ! -s "$TMPFILE" ]; then
        dialog --msgbox "No IP banned" 5 30
        rm -f "$TMPFILE"
        Fail2banMenu
    fi

    # Read the temporary file and construct the option for dialog
    devices=""
    while IFS= read -r line; do
        devices="$devices $line \"$line\" off"
    done < "$TMPFILE"

    # Use dialog to display the list of devices
    device=$(eval "dialog --radiolist \"Choose the IP to unban\" 0 0 0 $devices 3>&1 1>&2 2>&3")

    # Clean up and remove the temporary file
    rm -f "$TMPFILE"

    fail2ban-client unban "${device}"


}

ArchiveFail2banLog () {

    # Get the date and time in the desired format
    DATE=$(date "+%d-%m-%Y")
    TIME=$(date "+%H:%M:%S")

    # Path of the file to compress
    FILE="/var/log/fail2ban.log"

    # Check if the file to compress exists
    if [ ! -f "$FILE" ]; then
        dialog --msgbox "The file to compress does not exist" 5 40
        Fail2banMenu
    fi

    # Compressed file name
    COMPRESSED_FILE_NAME="fail2ban_${DATE}_${TIME}.xz"

    # Full path of the compressed file
    COMPRESSED_FILE_PATH="/var/log/${COMPRESSED_FILE_NAME}"

    # Compress the file
    xz "$FILE" -c > "$COMPRESSED_FILE_PATH"

    Fail2banMenu


}

Openfail2banLog () {

    pico /var/log/fail2ban.log

    Fail2banMenu
}

EnableForwardingIP () {

    dialog --yesno "Voulez-vous autoriser le routage IPv4 et IPv6 (Yes)\nou\nseulement IPv4 (No)" 7 70
    ipv6_ornot=$?

    if [ $ipv6_ornot -eq 0 ]; then

        sysctl -w net.inet.ip.forwarding=1 > /dev/null 2>&1
        sysctl -w net.inet6.ip6.forwarding=1 > /dev/null 2>&1

        # check if ip fowarding has already been added
        check=$(grep -o '# FORWARDING IP' < /etc/sysctl.conf | sort | uniq | wc -l | tr -d ' ')
        if [ "$check" -eq 0 ]; then

            printf "\n" >> /etc/sysctl.conf
            echo "# FORWARDING IP" >> /etc/sysctl.conf

            check1=$(grep -o 'net.inet.ip.forwarding=1' < /etc/sysctl.conf | sort | uniq | wc -l | tr -d ' ')
            if [ "$check1" -eq 0 ]; then

                echo "net.inet.ip.forwarding=1" >> /etc/sysctl.conf
                echo "net.inet6.ip6.forwarding=1" >> /etc/sysctl.conf

            fi

            check1=$(grep -o 'net.inet6.ip6.forwarding=1' < /etc/sysctl.conf | sort | uniq | wc -l | tr -d ' ')
            if [ "$check1" -eq 0 ]; then

                echo "net.inet6.ip6.forwarding=1" >> /etc/sysctl.conf

            fi



        else

            check1=$(grep -o 'net.inet.ip.forwarding=1' < /etc/sysctl.conf | sort | uniq | wc -l | tr -d ' ')
            if [ "$check1" -eq 0 ]; then

                echo "net.inet.ip.forwarding=1" >> /etc/sysctl.conf
                echo "net.inet6.ip6.forwarding=1" >> /etc/sysctl.conf

            fi

            check1=$(grep -o 'net.inet6.ip6.forwarding=1' < /etc/sysctl.conf | sort | uniq | wc -l | tr -d ' ')
            if [ "$check1" -eq 0 ]; then

                echo "net.inet6.ip6.forwarding=1" >> /etc/sysctl.conf

            fi


        fi


    else

        sysctl -w net.inet.ip.forwarding=1 > /dev/null 2>&1

        # check if ip fowarding has already been added
        check=$(grep -o '# FORWARDING IP' < /etc/sysctl.conf | sort | uniq | wc -l | tr -d ' ')
        if [ "$check" -eq 0 ]; then

            printf "\n" >> /etc/sysctl.conf
            echo "# FORWARDING IP" >> /etc/sysctl.conf

            check1=$(grep -o 'net.inet.ip.forwarding=1' < /etc/sysctl.conf | sort | uniq | wc -l | tr -d ' ')
            if [ "$check1" -eq 0 ]; then

                echo "net.inet.ip.forwarding=1" >> /etc/sysctl.conf

            fi

        else

            check1=$(grep -o 'net.inet.ip.forwarding=1' < /etc/sysctl.conf | sort | uniq | wc -l | tr -d ' ')
            if [ "$check1" -eq 0 ]; then

                echo "net.inet.ip.forwarding=1" >> /etc/sysctl.conf

            fi


        fi

    fi


    # check if activated :
    check=$(sysctl net.inet.ip.forwarding | grep -o "= [0-9]" | grep -o "[0-9]")
    if [ "$check" -eq 1 ]; then

        dialog --msgbox "IPv4 Forwading enabled" 5 26

    else

        dialog --msgbox "IPv4 Forwading disabled" 5 28

    fi

    check2=$(sysctl net.inet6.ip6.forwarding | grep -o "= [0-9]" | grep -o "[0-9]")
    if [ "$check2" -eq 1 ]; then

        dialog --msgbox "IPv6 Forwading enabled" 5 26

    else

        dialog --msgbox "IPv6 Forwading disabled" 5 28

    fi



    NetworkMenu
}

DisableForwardingIP () {

    sysctl -w net.inet.ip.forwarding=0 > /dev/null 2>&1
    sysctl -w net.inet6.ip6.forwarding=0 > /dev/null 2>&1

    sed '/^# FORWARDING IP/d' /etc/sysctl.conf
    sed '/^net.inet.ip.forwarding=1/d' /etc/sysctl.conf
    sed '/^net.inet6.ip6.forwarding=1/d' /etc/sysctl.conf


    # check if activated :
    check=$(sysctl net.inet.ip.forwarding | grep -o "= [0-9]" | grep -o "[0-9]")
    if [ "$check" -eq 1 ]; then

        dialog --msgbox "IPv4 Forwading enabled" 5 26

    else

        dialog --msgbox "IPv4 Forwading disabled" 5 28

    fi

    check2=$(sysctl net.inet6.ip6.forwarding | grep -o "= [0-9]" | grep -o "[0-9]")
    if [ "$check2" -eq 1 ]; then

        dialog --msgbox "IPv6 Forwading enabled" 5 26

    else

        dialog --msgbox "IPv6 Forwading disabled" 5 28

    fi

    NetworkMenu
}

PowerOff () {

    poweroff

}

RebooT () {

    reboot

}

#################
# MENUS

NetworkMenu () {
    # Your dialog command with dynamically calculated sizes
    choix1=$(dialog --clear \
                   --backtitle "NETWORK MENU" \
                   --title "Network Menu" \
                   --menu "Choose an option:" \
                   19 70 10 \
                   1 "Check Internet Connection" \
                   2 "Restart DHCP Service" \
                   - "------------------------------------------------------------" \
                   3 "Enable IP forwarding" \
                   4 "Disable IP forwarding" \
                   - "------------------------------------------------------------" \
                   5 "Switch from Ethernet to Wifi" \
                   6 "Connect to WiFi Network" \
                   7 "Switch from Wifi to Ethernet" \
                   - "------------------------------------------------------------" \
                   p "MAIN MENU" \
                   q "QUIT" \
                   3>&1 1>&2 2>&3)

    case $choix1 in
        1) checkInternetConnection ; ItsOkInternet ; NetworkMenu ;;
        2) RestartDHCP ;;
        3) EnableForwardingIP ;;
        4) DisableForwardingIP ;;
        -) NetworkMenu ;;
        5) SwitchToWifi ;;
        6) ConnectWifi ;;
        7) SwitchToEthernet ;;
        p|P) MainMenu ;;
        q|Q) exit 0 ;;
    esac

}

PareFeuMenu () {

    choix1=$(dialog --clear \
                   --backtitle "FIREWALL MENU" \
                   --title "Firewall Menu" \
                   --menu "Choose an option:" \
                   12 70 10 \
                   1 "Configure NPF" \
                   2 "View NPF Status and Active Rules" \
                   - "------------------------------------------------------------" \
                   r "PREVIOUS MENU" \
                   p "MAIN MENU" \
                   q "QUIT" \
                   3>&1 1>&2 2>&3)

    case $choix1 in
        1) PareFeu ;;
        2) ShowRulesNPF ;;
        -) PareFeuMenu ;;
        r|R) SecurityMenu ;;
        p|P) MainMenu ;;
        q|Q) exit 0 ;;
    esac

}


AntiVirusMenu () {

    choix1=$(dialog --clear \
                   --backtitle "ANTIVIRUS MENU" \
                   --title "AntiVirus Menu" \
                   --menu "Choose an option:" \
                   19 70 10 \
                   1 "Install ClamAV with securiteinfo/sanesecurity databases" \
                   2 "Update SaneSecurity ClamAV databases" \
                   - "------------------------------------------------------------" \
                   3 "Run a full antivirus scan" \
                   4 "Run an antivirus scan of /home" \
                   5 "Show ClamAV scan log" \
                   6 "Archive ClamAV log file" \
                   7 "Clear ClamAV log file" \
                   - "------------------------------------------------------------" \
                   r "PREVIOUS MENU" \
                   p "MAIN MENU" \
                   q "QUIT" \
                   3>&1 1>&2 2>&3)

    case $choix1 in
        1) installClamAV ;;
        2) UpdateSaneSecurityClamAV ;;
        -) AntiVirusMenu ;;
        3) FullScanClamAV ;;
        4) HomeScanClamAV ;;
        5) LogClamAV ;;
        6) ArchiveLogClamAV ;;
        7) CleanLogClamAV ;;
        r|R) SecurityMenu ;;
        p|P) MainMenu ;;
        q|Q) exit 0 ;;
    esac

}

Fail2banMenu () {
    # Your dialog command with dynamically calculated sizes
    choix=$(dialog --clear \
                   --backtitle "SECURITY MENU" \
                   --title "Security Menu" \
                   --menu "Choose an option:" \
                   19 70 10 \
                   1 "Configure Fail2ban" \
                   - "------------------------------------------------------------" \
                   2 "Show status" \
                   - "------------------------------------------------------------" \
                   3 "Open fail2ban log" \
                   4 "Archive fail2ban log" \
                   - "------------------------------------------------------------" \
                   5 "Show banned IP" \
                   6 "Unban an IP" \
                   - "------------------------------------------------------------" \
                   r "PREVIOUS MENU" \
                   p "MAIN MENU" \
                   q "QUIT" \
                   3>&1 1>&2 2>&3)

    case $choix in
        1) InstallFail2ban ;;
        2) Fail2banStatus ;;
        3) Openfail2banLog ;;
        4) ArchiveFail2banLog ;;
        5) ShowBannedIP ;;
        6) UnbanAnIP ;;
        -) Fail2banMenu ;;
        r|R) SecurityMenu;;
        p|P) MainMenu ;;
        q|Q) exit 0 ;;
    esac


}

SecurityMenu () {
    # Your dialog command with dynamically calculated sizes
    choix=$(dialog --clear \
                   --backtitle "SECURITY MENU" \
                   --title "Security Menu" \
                   --menu "Choose an option:" \
                   19 70 10 \
                   1 "Firewall" \
                   - "------------------------------------------------------------" \
                   2 "Configure SSH" \
                   - "------------------------------------------------------------" \
                   3 "Fail2ban" \
                   - "------------------------------------------------------------" \
                   4 "Anti-Virus" \
                   - "------------------------------------------------------------" \
                   5 "Set up OVPN VPN" \
                   - "------------------------------------------------------------" \
                   p "MAIN MENU" \
                   q "QUIT" \
                   3>&1 1>&2 2>&3)

    case $choix in
        1) PareFeuMenu ;;
        2) ConfigureSSH ;;
        3) Fail2banMenu ;;
        4) AntiVirusMenu ;;
        5) ovpnVPN ;;
        -) SecurityMenu ;;
        p|P) MainMenu ;;
        q|Q) exit 0 ;;
    esac
}

UsersRightsMenu () {
    # Your dialog command with dynamically calculated sizes
    choix=$(dialog --clear \
                   --backtitle "USERS AND ACCESS RIGHTS MENU" \
                   --title "Users and Access Rights Menu" \
                   --menu "Choose an option:" \
                   19 70 10 \
                   1 "Display list of users" \
                   2 "Create a user" \
                   3 "Check user existence" \
                   4 "Delete a user" \
                   - "-----------------------------------------------------------" \
                   5 "Display list of groups" \
                   6 "Create a group" \
                   7 "Check group existence" \
                   8 "Delete a group" \
                   9 "Add user to a group" \
                   10 "Remove user from a group" \
                   - "-----------------------------------------------------------" \
                   11 "Install sudo and add user to sudo group" \
                   - "-----------------------------------------------------------" \
                   p "MAIN MENU" \
                   q "QUIT" \
                   3>&1 1>&2 2>&3)

    case $choix in
        1) getentPasswd ;;
        2) CreateUser ;;
        3) CheckUserExists ;;
        4) DeleteUser ;;
        5) getentGroup ;;
        6) CreateGroup ;;
        7) CheckGroupExists ;;
        8) DeleteGroup ;;
        9) AddToGroup ;;
        10) LeaveGroup ;;
        11) InstallSudo ;;
        -) UsersRightsMenu ;;
        p|P) MainMenu ;;
        q|Q) exit 0 ;;
    esac
}


InstallProgramsMenu () {
    choix=$(dialog --clear \
                   --backtitle "PROGRAM INSTALLATION MENU" \
                   --title "Program Installation Menu" \
                   --menu "Choose an option:" \
                   13 70 10 \
                   1 "Install desktop applications" \
                   2 "Install usual utilities" \
		   3 "Install Build Tools" \
                   - "------------------------------------------------------------" \
                   p "MAIN MENU" \
                   q "QUIT" \
                   3>&1 1>&2 2>&3)

    case $choix in
        1) DesktopBundleApps ;;
        2) UsualTools ;;
	3) BuildTools ;;
        -) InstallProgramsMenu ;;
        p|P) MainMenu ;;
        q|Q) exit 0 ;;
    esac
}



NetServices () {

    dialog --msgbox "Not yet ready" 5 17
    MainMenu

}

DiskMngmtMenu () {
    choix=$(dialog --clear \
                   --backtitle "DISK MANAGEMENT MENU" \
                   --title "Disk Management Menu" \
                   --menu "Choose an option:" \
                   18 70 10 \
                   1 "Format a USB device to FFSv1" \
                   2 "Format a USB device to FFSv2" \
                   3 "Format a USB device to NTFS" \
                   4 "Format a USB device to EXFAT (not fully working)" \
                   5 "Securely erase a USB device" \
                   - "------------------------------------------------------------" \
                   6 "Mount a USB device to /media/dkX" \
                   7 "Unmount a USB device mounted to /media/dkX" \
                   - "------------------------------------------------------------" \
                   8 "Burn .iso to a USB device" \
                   9 "Burn .iso to a CD" \
                   - "------------------------------------------------------------" \
                   10 "Rebuild locate index" \
                   - "------------------------------------------------------------" \
                   p "MAIN MENU" \
                   q "QUIT" \
                   3>&1 1>&2 2>&3)

    case $choix in
        1) FormatToFFSv1 ;;
        2) FormatToFFSv2 ;;
        3) FormatToNTFS ;;
        4) FormatToEXFAT ;;
        5) SecurelyErase ;;
        6) mountUSB ;;
        7) umountUSB ;;
        8) BurnISOtoUSB ;;
        9) BurnISOtoCD ;;
        10) locateRebuild ;;
        -) DiskMngmtMenu ;;
        p|P) MainMenu ;;
        q|Q) exit 0 ;;
    esac
}

OpenSSHFSMenu () {
    choix=$(dialog --clear \
                   --backtitle "OPENSSH FILE SERVER MENU" \
                   --title "OpenSSH File Server Menu" \
                   --menu "Choose an option:" \
                   19 70 10 \
                   1 "Configure a SFTP file server with OpenSSH" \
                   - "------------------------------------------------------------" \
                   2 "Create a SFTP user" \
                   3 "List SFTP users" \
                   4 "Delete a SFTP user" \
                   5 "Change password for a SFTP user" \
                   - "------------------------------------------------------------" \
                   6 "Disable a SFTP user account" \
                   7 "List SFTP disabled users" \
                   8 "Re-enable a SFTP user account" \
                   - "------------------------------------------------------------" \
                   p "MAIN MENU" \
                   q "QUIT" \
                   3>&1 1>&2 2>&3)

    case $choix in
        1) SFTPFS ;;
        -) OpenSSHFSMenu ;;
        2) CreateSFTPuser ;;
        3) ListSFTPusers ;;
        4) DeleteSFTPuser ;;
        5) ChangepassSFTPuser ;;
        6) DisableSFTPuser ;;
        7) ListDisabledSFTPusers ;;
        8) RenableSFTPuser ;;
        p|P) MainMenu ;;
        q|Q) exit 0 ;;
    esac
}

ServicesMenu () {
    choix=$(dialog --clear \
                   --backtitle "SERVICES MENU" \
                   --title "Services Menu" \
                   --menu "Choose an option:" \
                   11 70 10 \
                   1 "OpenSSH File Server" \
                   - "------------------------------------------------------------" \
                   p "MAIN MENU" \
                   q "QUIT" \
                   3>&1 1>&2 2>&3)

    case $choix in
        1) OpenSSHFSMenu ;;
        -) ServicesMenu ;;
        p|P) MainMenu ;;
        q|Q) exit 0 ;;
    esac
}


DesktopMenu () {
    choix=$(dialog --clear \
                   --backtitle "DESKTOP ENVIRONMENT MENU" \
                   --title "Desktop Environment Menu" \
                   --menu "Choose an option:" \
                   11 70 10 \
                   1 "Install XFCE4/Slim desktop environment" \
                   - "------------------------------------------------------------" \
                   p "MAIN MENU" \
                   q "QUIT" \
                   3>&1 1>&2 2>&3)

    case $choix in
        1) xfce4 ;;
        -) DesktopMenu ;;
        p|P) MainMenu ;;
        q|Q) exit 0 ;;
    esac
}




###############################################################################

MainMenu () {
    choix=$(dialog --clear \
                   --backtitle "WELCOME TO THE GLOBAL NETBSD SCRIPT" \
                   --title "Main Menu" \
                   --menu "Choose an option:" \
                   19 70 10 \
                   h "README" \
                   - "------------------------------------------------------------" \
                   1 "Network" \
                   2 "Security" \
                   3 "Users and Permissions" \
                   4 "Programs" \
                   5 "Web Server" \
                   6 "Disk Management" \
                   7 "Services" \
                   8 "Desktop Environment" \
                   - "------------------------------------------------------------" \
                   q "QUIT" \
                   - "------------------------------------------------------------" \
                   s "POWER OFF" \
                   x "REBOOT" \
                   3>&1 1>&2 2>&3)

    case $choix in
        h) READMEMenu ;;
        1) NetworkMenu ;;
        2) SecurityMenu ;;
        3) UsersRightsMenu ;;
        4) InstallProgramsMenu ;;
        5) NetServices ;;
        6) DiskMngmtMenu ;;
        7) ServicesMenu ;;
        8) DesktopMenu ;;
        -) MainMenu ;;
        q|Q) exit 0 ;;
        s|S) PowerOff ;;
        x|X) RebooT ;;
    esac
}


###############################################################################

READMEMenu () {

    choix=$(dialog --clear \
                   --backtitle "README MENU" \
                   --title "README Menu" \
                   --menu "Choose an option:" \
                   18 70 10 \
                   1 "Read Me First" \
                   - "------------------------------------------------------------" \
                   p "MAIN MENU" \
                   q "QUIT" \
                   3>&1 1>&2 2>&3)

    case $choix in
        1) ReadMeFirst ;;
        -) READMEMenu ;;
        p|P) MainMenu ;;
        q|Q) exit 0 ;;
    esac
}

ReadMeFirst() {

echo "Welcome to this server configuration module for NetBSD!
------------------------------------------------------------

First of all, this module should only be executed on a fresh installation of NetBSD 9.3/10.
It should not be executed on an already configured and production server as the scripts it contains could interact with the existing server configurations and potentially cause damage.

I decline any responsibility regarding the execution of this module.

The purpose of this module is primarily to facilitate basic server management tasks on a NetBSD server by providing a fully automated configuration of many services through a minimalist graphical interface.
It can also serve as a source of functional commands and syntaxes under NetBSD standard shell.

Of course, it is graciously made available to the public and can be modified by anyone without any form of compensation (except a thank you, if you feel like it).

If you spot any faulty features (or bad english :-S ! I'm french) or wish to discuss the possibility of adding new features and collaborate, you can contact me: theophile.dudreuilh@yahoo.com" > /tmp/AEzevinvpin.tmp

fold -s -w 67 /tmp/AEzevinvpin.tmp > /tmp/aaevpinpaeinEAB.tmp

dialog --title "Read Me First" --textbox /tmp/aaevpinpaeinEAB.tmp 20 70
}




# Appel du menu
MainMenu
