#!/bin/bash
# prevents weirdness over tty
export NCURSES_NO_UTF8_ACS=1
export TERM=xterm-256color
export LANG=C.UTF-8

if [[ $EUID -ne 0 ]]; then
  echo "This script must be run as root."
  echo "Try \`sudo femto-config\`."
  exit 1
fi

# pause
pause() {
  echo "Press any key to continue..."
  read -n 1 -s -r
}

# Dialog uses a different method to display colors, and is limited to only these 8.
replace_colors() {
  input="$1"
  input="${input//$(echo -e '\033[0;30m')/\\Z0}"   # black
  input="${input//$(echo -e '\033[0;31m')/\\Z1}"   # red
  input="${input//$(echo -e '\033[0;32m')/\\Z2}"   # green
  input="${input//$(echo -e '\033[0;33m')/\\Z3}"   # yellow
  input="${input//$(echo -e '\033[0;34m')/\\Z4}"   # blue
  input="${input//$(echo -e '\033[0;35m')/\\Z5}"   # magenta
  input="${input//$(echo -e '\033[0;36m')/\\Z6}"   # cyan
  input="${input//$(echo -e '\033[0;37m')/\\Z7}"   # white
  input="${input//$(echo -e '\033[7m')/\\Zr}"      # invert
  input="${input//$(echo -e '\033[4m')/\\Zu}"      # underline
  input="${input//$(echo -e '\033[0m')/\\Zn}"      # reset
  echo "$input"
}

loading() {
  dialog --no-collapse --infobox "$1" 5 45
}

wifi_config() {
  local wifi_ssid=""
  local wifi_psk=""
  local wifi_country=""
  wifi_ssid=$(dialog --no-collapse --title "$title2" --inputbox "Enter Wi-Fi SSID:" 8 40 "$(grep -oP '^ *ssid="\K[^"]+' /etc/wpa_supplicant/wpa_supplicant.conf)" 3>&1 1>&2 2>&3) # display current SSID
  wifi_psk=$(dialog --no-collapse --title "$title2" --inputbox "Enter Wi-Fi Password:" 8 40 3>&1 1>&2 2>&3)
  wifi_country=$(dialog --no-collapse --title "$title2" --inputbox "Enter Country Code (US, DE...):" 8 40 "$(grep -oP '^ *country=\K[^ ]+' /etc/wpa_supplicant/wpa_supplicant.conf)" 3>&1 1>&2 2>&3) # display current country
  cmd="femto-network-config.sh -s \"$wifi_ssid\" -p \"$wifi_psk\""
  [ -n "$wifi_country" ] && cmd="$cmd -c \"$wifi_country\""
  cmd="$cmd -r"
  if [ -z "$wifi_ssid" ]; then
    dialog --no-collapse --title "$title2" --msgbox "\nSSID is required to configure Wi-Fi." 7 40
    return
  fi
  echo "Configuring wifi..."
  eval $cmd &>/dev/null
  dialog --no-collapse --title "$title2" --msgbox "Wi-Fi Settings Saved:\nSSID: $wifi_ssid\nPassword: (hidden)\nCountry: $wifi_country\nMeshtastic Wi-Fi setting set to ON" 9 40
  if [ "$1" = "-w" ]; then
    exit 0
  fi
}

# Function to handle Wi-Fi settings
networking_settings() {
  local title="Networking"
  local title2="Wi-Fi (wlan0) Settings"
  ip=$(hostname -I | sed 's/ / /g'); ip=${ip:+$(printf "IPv4 address:\n%s" "$ip")}
  wpa_supplicant_conf="/etc/wpa_supplicant/wpa_supplicant.conf"
  choice=""   # zero the choice before loading the submenu
  while true; do
    networking_choice=$(dialog --no-collapse --cancel-label "Back" --default-item "$networking_choice" --title "$title" --menu "$ip" $([ -z "$ip" ] && echo 16 || echo 18) 40 4 \
      1 "Turn Wi-Fi on/off" \
      2 "View Wi-Fi settings" \
      3 "Change Wi-Fi settings" \
      4 "View ethernet settings" \
      5 "Restart networking" \
      6 "Set hostname" \
      7 "Test internet connection" \
      " " "" \
    8 "Back to main menu" 3>&1 1>&2 2>&3)
    
    exit_status=$? # This line checks the exit status of the dialog command
    if [ $exit_status -eq 1 ]; then # Exit the loop if the user selects "Cancel" or closes the dialog
      break
    fi
    
    case $networking_choice in
      1) # Turn Wi-Fi on/off)
        if ! ip link show wlan0 &>/dev/null; then
          dialog --no-collapse --colors --msgbox "\Z1Network adapter wlan0 does not exist.\Zn\n\nIs a wifi adapter connected?" 8 40
        else
          while true; do
            choice=$(dialog --no-collapse --cancel-label "Back" --default-item "$choice" --title "Enable/disable Wi-Fi" --menu "Tip: Wi-Fi can also be toggled by short-pressing the BOOT button on the Luckfox." 13 50 5 \
              1 "Turn Wi-Fi on" \
              2 "Turn Wi-Fi off" \
              " " "" \
              3 "Return to previous menu" 3>&1 1>&2 2>&3)
            exit_status=$? # This line checks the exit status of the dialog command
            if [ $exit_status -eq 1 ]; then # Exit the loop if the user selects "Cancel" or closes the dialog
              break
            fi
            case $choice in
              1) femto-network-config.sh -x "up" && break ;;
              2) femto-network-config.sh -x "down" && break ;;
              3) break ;;
            esac
          done
        fi
      ;;
      2) # View Wi-Fi settings)
        echo "Getting Wi-Fi configuration..."
        dialog --no-collapse --title "$title2" --colors --msgbox "$(replace_colors "$(femto-network-config.sh -w)")" 0 0
      ;;
      3) # Change Wi-Fi settings)
        wifi_config
      ;;
      4) # View ethernet settings)
        echo "Getting ethernet configuration..."
        dialog --no-collapse --title "Ethernet (eth0) settings" --colors --msgbox "$(echo -e "$(replace_colors "$(femto-network-config.sh -e)")")" 0 0
      ;;
      5) # Restart networking)
        dialog --no-collapse --title "$title2" --yesno "Wi-Fi and Ethernet will be restarted.\nMeshtastic Wi-Fi setting will be set to ON.\n\nProceed?" 10 40
        if [ $? -eq 0 ]; then #unless cancel/no
          femto-network-config.sh -r
        fi
      ;;
      6) # set hostname)
        new_hostname=$(dialog --no-collapse --title "$title" --inputbox "Enter new hostname:" 8 40 $(hostname) 3>&1 1>&2 2>&3)
        if [ $? -eq 0 ]; then #unless cancel/no
          femto-network-config.sh -n "$new_hostname"
          dialog --no-collapse --title "$title" --msgbox "Femtofox is now reachable at\n$new_hostname.local" 8 40
        fi
      ;;
      7) # Test internet connection)
        loading "Testing internet connection..."
        dialog --no-collapse --title "Internet connectivity test" --colors --msgbox "$(replace_colors "$(femto-network-config.sh -t)")" 8 40
      ;;
      8)
        return
      ;;
    esac
  done
}

# utilities
utilities() {
  local title="Utilities"
  while true; do
    utilities_choice=$(dialog --no-collapse --cancel-label "Back" --default-item "$utilities_choice" --menu "$title" 21 50 4 \
      1 "View system info" \
      2 "Set system time" \
      3 "Kernel modules" \
      4 "Re-run first-boot script" \
      5 "Run USB configuration tool" \
      6 "Run OEM luckfox-config" \
      7 "Process viewer/manager" \
      8 "Disable/enable logging" \
      9 "Disable/enable activity LED" \
      10 "Reboot" \
      11 "Shutdown" \
      " " "" \
      12 "Back to main menu" 3>&1 1>&2 2>&3)
    
    exit_status=$? # This line checks the exit status of the dialog command
    if [ $exit_status -eq 1 ]; then # Exit the loop if the user selects "Cancel" or closes the dialog
      break
    fi
    
    case $utilities_choice in
      1)
        choice=""   # zero the choice before loading the submenu
        while true; do
          choice=$(dialog --no-collapse --help-button --help-label "Help" --cancel-label "Back" --default-item "$choice" --menu "System info" 17 40 5 \
            1 "CPU" \
            2 "Operating system" \
            3 "Storage & memory" \
            4 "Peripherals & devices" \
            5 "Networking" \
            6 "Meshtastic node info" \
            7 "Complete system info" \
            " " "" \
            8 "Back to previous menu" 3>&1 1>&2 2>&3)
          exit_status=$? # This line checks the exit status of the dialog command
          if [ $exit_status -eq 1 ]; then # Exit the loop if the user selects "Cancel" or closes the dialog
            break
          elif [ $exit_status -eq 2 ]; then # Help ("extra") button
            dialog --no-collapse --colors --title "System info help" --msgbox "To get system info in terminal (where it can be copied), enter \`\Zusudo femto-utils.sh -i\Zn\`.\n\nWhen getting Peripherals & Devices (or Complete System Info) without an i2c device connected, it is normal to see error messages on serial console.\n" 0 0
          else
            case $choice in
              1) # CPU)
                loading "Loading CPU info..."
                dialog --no-collapse --colors --title "CPU info" --msgbox "$(replace_colors "$(femto-utils.sh -c)")" 0 0
              ;;
              2) # Operating system)
                loading "Loading operating system info..."
                dialog --no-collapse --colors --extra-button --title "Operating system" --msgbox "$(replace_colors "$(femto-utils.sh -o)")" 0 0
              ;;
              3) # Storage & memory)
                loading "Loading storage & memory info..."
                dialog --no-collapse --colors --title "Storage & memory" --msgbox "$(replace_colors "$(femto-utils.sh -S)")" 0 0
              ;;
              4) # Peripherals & devices)
                loading "Loading peripherals & devices info..."
                dialog --no-collapse --colors --title "Peripherals & devices" --msgbox "$(replace_colors "$(femto-utils.sh -p)")" 0 0
              ;; 
              5) # Networking)
                loading "Loading networking info..."
                dialog --no-collapse --colors --title "Networking" --msgbox "$(replace_colors "$(femto-utils.sh -n)")" 0 0
              ;;
              6) # Meshtastic node info)
                loading "Loading Meshtastic node info..."
                dialog --no-collapse --colors --title "Meshtastic node info" --msgbox "$(replace_colors "$(femto-meshtasticd-config.sh -i)")" 0 0
              ;;
              7) # Complete system info)
                loading "Loading complete system info..."
                dialog --no-collapse --colors --title "System info" --msgbox "$(replace_colors "$(femto-utils.sh -i)")" 0 0
              ;;
              8) break ;;
            esac
          fi
        done
      ;;
      2) femto-set-time.sh ;; # set timezone
      3) # Kernel modules)
        dialog --no-collapse --title "$title" --msgbox "Kernel modules are loadable pieces of code that extend a Linux kernel's functionality without requiring a reboot. Common examples include device drivers, file systems, or system calls.\n\nThis tool will allow you to add pre-compiled modules to the Foxbuntu kernel.\n\nModules currently autostarting at boot: $(modules=$(sed -n '6,$p' /etc/modules | sed ':a;N;$!ba;s/\n/, /g;s/, $//'); [ -z "$modules" ] && echo "none" || echo "$modules")\n\nCurrently active modules: $(lsmod | awk 'NR>1 {print $1}' | tr '\n' ' ')" 18 65
        femto-kernel-modules.sh
      ;;
      4) femto-runonce.sh ;; # Re-run first-boot script
      5) # USB config)
        dialog --no-collapse --title "$title" --yesno "The USB configuration tool allows you to set critical Femtofox settings with a text file on a USB flash drive.\n\nFor more information, visit\ngithub.com/femtofox/femtofox/blob/main/usb_config.md\n\nThis tool is run automatically at boot.\n\nRun now?" 14 60
        if [ $? -eq 0 ]; then #unless cancel/no
          femto-usb-config-tool.sh
          pause
        fi
      ;;
      6) luckfox-config ;;
      7) htop ;;
      8) # logging)
        choice=""   # zero the choice before loading the submenu
        while true; do
          choice=$(dialog --no-collapse --colors --title "Logging" --cancel-label "Back" --default-item "$choice" --menu "Before deploying a Femtofox, it is advisable to disable logging to reduce SD card wear.\nCurrent state: $(replace_colors "$(femto-utils.sh -l "check")")" 14 50 2 \
            1 "Enable (default)" \
            2 "Disable" \
            " " "" \
            3 "Return to previous menu" 3>&1 1>&2 2>&3)
          exit_status=$? # This line checks the exit status of the dialog command
          if [ $exit_status -eq 1 ]; then # Exit the loop if the user selects "Cancel" or closes the dialog
            break
          fi
          case $choice in
            1) femto-utils.sh -l "enable" ;;
            2) femto-utils.sh -l "disable" ;;
            3) break ;;
          esac
        done
      ;;
      9) # logging)
        choice=""   # zero the choice before loading the submenu
        while true; do
          choice=$(dialog --no-collapse --colors --title "Logging" --cancel-label "Back" --default-item "$choice" --menu "Before deploying a Femtofox, it is advisable to disable the Activity LED to save power.\nCurrent state: $(replace_colors "$(femto-utils.sh -a "check")")" 14 50 2 \
            1 "Enable (default)" \
            2 "Disable" \
            " " "" \
            3 "Return to previous menu" 3>&1 1>&2 2>&3)
          exit_status=$? # This line checks the exit status of the dialog command
          if [ $exit_status -eq 1 ]; then # Exit the loop if the user selects "Cancel" or closes the dialog
            break
          fi
          case $choice in
            1) femto-utils.sh -a "enable" ;;
            2) femto-utils.sh -a "disable" ;;
            3) break ;;
          esac
        done
      ;;
      10) # reboot)
        dialog --no-collapse --title "$title" --yesno "Reboot now?\n\nTip: Reboot can also be triggered by long-pressing the BOOT button on the luckfox." 10 45
        if [ $? -eq 0 ]; then #unless cancel/no
          loading "Rebooting..."
          femto-utils.sh -r
        fi
      ;;
      11) # shutdown)
        dialog --no-collapse --colors --title "$title" --yesno "Shut down now?\n\nTo power system back on, disconnect/reconnect power.\n\nThe system shutdown command prevents damage to the filesystem from power interrupts, but does not stop power consumption.\n\nTip: You can also shut down the Femtofox by pressing the BOOT button for 5 seconds or by running \`\Zusudo halt\Zn\`." 14 60
        if [ $? -eq 0 ]; then #unless cancel/no
          loading "Shutting down...\n\nPower consumption will not stop."
          femto-utils.sh -s
        fi
      ;;
      12) return ;;
    esac
  done
}

#set lora radio
set_lora_radio() {
  choice=""   # zero the choice before loading the submenu
  while true; do
    echo "Checking LoRa radio..."
    #Display filename, if exists: $(files=$(ls /etc/meshtasticd/config.d/* 2>/dev/null) && [ -n "$files" ] && echo "\n\nConfiguration files in use:\n$files" | paste -sd, -))
    choice=$(dialog --no-collapse --colors --cancel-label "Back" --default-item "$choice" --title "Meshtastic LoRa radio" --menu "Currently configured LoRa radio:\n$(replace_colors "$(femto-meshtasticd-config.sh -k)")$(ls -1 /etc/meshtasticd/config.d 2>/dev/null | paste -sd ', ' - | sed 's/^/ (/; s/$/)/; s/,/, /g' | grep -v '^ ()$')" 19 50 10 \
       "Ebyte e22-900m30s" "(SX1262_TCXO)" \
       "Ebyte e22-900m22s" "(SX1262_TCXO)"\
       "Ebyte e80-900m22s" "(SX1262_XTAL)"\
       "Heltec ht-ra62" "(SX1262_TCXO)"\
       "Seeed wio-sx1262" "(SX1262_TCXO)"\
       "Waveshare sx126x-xxxm" "(SX1262_XTAL)"\
       "AI Thinker ra-01sh" "(SX1262_XTAL)"\
       "None" "(simulated radio)"\
      " " "" \
    "Skip" "" 3>&1 1>&2 2>&3)
    
    exit_status=$? # This line checks the exit status of the dialog command
    if [ $exit_status -eq 1 ]; then # Exit the loop if the user selects "Cancel" or closes the dialog
      break
    fi
    
    local radio=""
    case $choice in
      "Ebyte e22-900m30s")
        radio="sx1262_tcxo"
      ;;
      "Ebyte e22-900m22s")
        radio="sx1262_tcxo"
      ;;
      "Ebyte e80-900m22s")
        radio="sx1262_xtal"
      ;;
      "Heltec ht-ra62")
        radio="sx1262_tcxo"
      ;;
      "Seeed wio-sx1262")
        radio="sx1262_tcxo"
      ;;
      "Waveshare sx126x-xxxm")
        radio="sx1262_xtal"
      ;;
      "AI Thinker ra-01sh")
        radio="sx1262_xtal"
      ;;
      "None")
        radio="none"
      ;;
      "Skip")
        return
      ;;
    esac
    if [ -n "$radio" ]; then #if a radio was selected
      femto-meshtasticd-config.sh -l "$radio" -s # set the radio, then restart meshtasticd
      return
    fi
  done
}

# Function to handle Meshtasticd settings
meshtastic_settings() {
  local title="Meshtastic Settings"
  while true; do
    echo "Checking Meshtasticd service state..."
    meshtastic_choice=$(dialog --no-collapse --colors --title "$title" --cancel-label "Back" --default-item "$meshtastic_choice" --menu "Meshtasticd service is $(replace_colors "$(femto-meshtasticd-config.sh -S)")$(femto-meshtasticd-config.sh -k | grep -q 'simulated' && echo '\n\Z1Warning: using simulated radio\Zn')" 19 50 4 \
      1 "View node info" \
      2 "View configuration URL & QR code" \
      3 "Set new configuration URL" \
      4 "Set LoRa radio" \
      5 "Security settings" \
      6 "Mesh connectivity test" \
      7 "Manage Meshtasticd service" \
      8 "Upgrade/install Meshtasticd" \
      9 "Uninstall Meshtasticd" \
      " " "" \
    10 "Back to main menu" 3>&1 1>&2 2>&3)
    
    exit_status=$? # This line checks the exit status of the dialog command
    if [ $exit_status -eq 1 ]; then # Exit the loop if the user selects "Cancel" or closes the dialog
      break
    fi
    
    case $meshtastic_choice in
      1) # view node info)
        loading "Getting node info..."
        dialog --no-collapse --colors --title "Node info" --msgbox "$(replace_colors "$(femto-meshtasticd-config.sh -i)")" 0 0
        ;;
      2) # get current configuration URL & QR code)
        loading "Getting Meshtastic QR code and URL..."
        femto-meshtasticd-config.sh -g
        pause
      ;;
      3) # set URL)
        newurl=$(dialog --no-collapse --title "Meshtastic URL" --inputbox "New Meshtastic LoRa configuration URL (SHIFT+INS to paste):" 8 60 3>&1 1>&2 2>&3)
        if [ -n "$newurl" ]; then #if a URL was entered
          dialog --no-collapse --title "$title" --yesno "New Meshtastic LoRa configuration URL:\n$newurl\n\nConfirm?" 15 60
          if [ $? -eq 0 ]; then #unless cancel/no
            loading "Sending command..."
            dialog --no-collapse --colors --title "Meshtastic URL" --msgbox "$(femto-meshtasticd-config.sh -q "$newurl" && echo -e "\n\Z4Command successful!\Zn\n" || echo -e "\n\Z1Command failed.\Zn\n")" 0 0
          fi
        fi
      ;;
      4) # set radio)
        set_lora_radio
      ;;
      5) # remote admin)
        choice=""   # zero the choice before loading the submenu
        while true; do
          choice=$(dialog --no-collapse --cancel-label "Back" --default-item "$choice" --title "Meshtastic Security Settings" --menu "" 16 40 5 \
            1 "View/change public key" \
            2 "View/change private key" \
            " " "" \
            3 "View admin keys" \
            4 "Set admin key" \
            5 "Clear admin keys" \
            6 "Legacy admin channel" \
            " " "" \
            7 "Return to previous menu" 3>&1 1>&2 2>&3)
          exit_status=$? # This line checks the exit status of the dialog command
          if [ $exit_status -eq 1 ]; then # Exit the loop if the user selects "Cancel" or closes the dialog
            break
          fi
          case $choice in
            1) # view/change public key)
              loading "Getting current public key..."
              key=$(femto-meshtasticd-config.sh -u)
              if [ -n "$key" ]; then
                dialog --no-collapse --title "Meshtastic public key" --yesno "Current public key:\n$key\n\nSet new key?" 9 55
                if [ $? -eq 0 ]; then #unless cancel/no
                  key=$(dialog --no-collapse --title "Meshtastic public key" --inputbox "New Meshtastic public key (SHIFT+INS to paste):" 8 60 3>&1 1>&2 2>&3)
                  if [ $? -eq 0 ]; then #unless cancel/no
                    loading "Sending command..."
                    dialog --no-collapse --colors --title "Meshtastic public key" --msgbox "$(femto-meshtasticd-config.sh -U "$key" && echo -e "\n\Z4Command successful!\Zn\n" || echo -e "\n\Z1Command failed.\Zn\n")" 0 0
                  fi
                fi
              else
                dialog --no-collapse --colors --title "Meshtastic public key" --msgbox "\Z1Failed to communicate with Meshtasticd.\Zn\n\nIs the service running?\n" 0 0
              fi
            ;;
            2) # view/change private key)
              loading "Getting current private key..."
              key=$(femto-meshtasticd-config.sh -u)
              if [ -n "$key" ]; then
                dialog --no-collapse --title "Meshtastic private key" --yesno "Current private key:\n$key\n\nSet new key?" 9 55
                if [ $? -eq 0 ]; then #unless cancel/no
                  key=$(dialog --no-collapse --title "Meshtastic private key" --inputbox "New Meshtastic private key (SHIFT+INS to paste):" 8 60 3>&1 1>&2 2>&3)
                  if [ $? -eq 0 ]; then #unless cancel/no
                    loading "Sending command..."
                    dialog --no-collapse --colors --title "Meshtastic private key" --msgbox "$(femto-meshtasticd-config.sh -R "$key" && echo -e "\n\Z4Command successful!\Zn\n" || echo -e "\n\Z1Command failed.\Zn\n")" 0 0
                  fi
                fi
              else
                dialog --no-collapse --colors --title "Meshtastic private key" --msgbox "\Z1Failed to communicate with Meshtasticd.\Zn\n\nIs the service running?\n" 0 0
              fi
            ;;
            3) # view admin keys)
              loading "Getting Admin Keys..."
              dialog --no-collapse --title "Admin keys" --msgbox "Up to 3 admin keys are permitted, more will be ignored.\n\nKeys:$(femto-meshtasticd-config.sh -a | tail -n 1 | sed 's/|n/\\n/g')" 0 0
            ;;
            4) # set admin key)
              key=$(dialog --no-collapse --title "Admin Keys" --inputbox "Meshtastic admin key - up to 3, more will be ignored.\n\n(SHIFT+INS to paste):" 11 40 3>&1 1>&2 2>&3)
              if [ -n "$key" ]; then #if a key was entered
                loading "Sending command..."
                dialog --no-collapse --colors --title "Admin Keys" --msgbox "$(femto-meshtasticd-config.sh -A "$key" && echo -e "\n\Z4Command successful!\Zn\n" || echo -e "\n\Z1Command failed.\Zn\n")" 0 0
              fi
            ;;
            5) # clear admin keys)
              dialog --no-collapse --title "Admin Keys" --yesno "Meshtasticd can have up to 3 admin keys. If more are added, they will be ignored.\n\nClear admin key list?\n" 0 0
              if [ $? -eq 0 ]; then #unless cancel/no
                loading "Sending command..."
                dialog --no-collapse --colors --title "Admin Keys" --msgbox "$(femto-meshtasticd-config.sh -c && echo -e "\n\Z4Command successful!\Zn\n" || echo -e "\n\Z1Command failed.\Zn\n")" 0 0
              fi
            ;;
            6) # legacy admin)
              choice=""   # zero the choice before loading the submenu
              while true; do
                loading "Getting current legacy admin state..."
                choice=$(dialog --no-collapse --colors --title "Legacy Admin" --default-item "$choice" --menu "Current state: $(replace_colors "$(femto-meshtasticd-config.sh -p)")" 12 40 5 \
                  1 "Enable" \
                  2 "Disable (default)" \
                  " " "" \
                  3 "Return to previous menu" 3>&1 1>&2 2>&3)
                exit_status=$? # This line checks the exit status of the dialog command
                if [ $exit_status -eq 1 ]; then # Exit the loop if the user selects "Cancel" or closes the dialog
                  break
                fi
                case $choice in
                  1) # enable legacy admin)
                    dialog --no-collapse --title "Legacy Admin" --yesno "Enable legacy admin channel?\n" 0 0
                    if [ $? -eq 0 ]; then #unless cancel/no
                      loading "Sending command..."
                      dialog --no-collapse --colors --title "Legacy admin" --msgbox "$(femto-meshtasticd-config.sh -o "true" && echo -e "\n\Z4Command successful!\Zn\n" || echo -e "\n\Z1Command failed.\Zn\n")" 0 0
                    fi
                  ;;
                  2) # disable legacy admin)
                    dialog --no-collapse --title "Legacy Admin" --yesno "Disable legacy admin channel?\n" 0 0
                    if [ $? -eq 0 ]; then #unless cancel/no
                      loading "Sending command..."
                      dialog --no-collapse --colors --title "Legacy admin" --msgbox "$(femto-meshtasticd-config.sh -o "false" && echo -e "\n\Z4Command successful!\Zn\n" || echo -e "\n\Z1Command failed.\Zn\n")" 0 0
                    fi
                  ;;
                  3) break ;;
                esac
              done
            ;;
            7) # return to previous menu)
              break
            ;;            
          esac
        done
      ;;
      6) #test mesh connectivity)
        dialog --no-collapse --title "Meshtastic Connectivity Test" --yesno "Will send \"test\" to channel 0 and wait for acknowledgement. Will try up to 3 times.\n\nPerform test?" 10 45
        if [ $? -eq 0 ]; then #unless cancel/no
          dialog --no-collapse --infobox "Performing mesh connectivity test.\n\nThis may take a while..." 6 45
          dialog --no-collapse --colors --title "Meshtasticd service status" --msgbox "$(replace_colors "$(femto-meshtasticd-config.sh -w)")" 0 0
        fi
      ;;
      7) #manage meshtasticd service)
        choice=""   # zero the choice before loading the submenu
        while true; do
          echo "Checking Meshtasticd service state..."
          local service_state="$(replace_colors "$(femto-meshtasticd-config.sh -S)")"
          choice=$(dialog --no-collapse --colors --cancel-label "Back" --title "Meshtasticd Service" --default-item "$choice" --menu "Meshtasticd service is $service_state$(femto-meshtasticd-config.sh -k | grep -q 'simulated' && echo '\n\Z1Using simulated radio\Zn')" 17 52 5 \
            "View detailed service status" "x" \
            " " " " \
            $(if echo "$service_state" | grep -q 'enabled'; then echo "Start/restart service x"; fi) \
            $(if echo "$service_state" | grep -q 'enabled and running'; then echo "Stop service x"; fi) \
            $(if echo "$service_state" | grep -q 'enabled'; then echo "   "; fi) \
            $(if echo "$service_state" | grep -q 'disabled'; then echo "Enable service x"; fi) \
            $(if echo "$service_state" | grep -q 'enabled'; then echo "Disable service x"; fi) \
            " " " " \
            "Back to previous menu" "x" 3>&1 1>&2 2>&3)
          exit_status=$? # This line checks the exit status of the dialog command
          if [ $exit_status -eq 1 ]; then # Exit the loop if the user selects "Cancel" or closes the dialog
            break
          fi
          case $choice in
            "View detailed service status") 
              loading "Getting Meshtasticd service status..."
              dialog --no-collapse --title "Meshtasticd service status" --msgbox "$(systemctl status meshtasticd)" 0 0
            ;;
            "Start/restart service") 
              dialog --no-collapse --title "$title" --yesno "Start/restart Meshtasticd service?" 6 45
              if [ $? -eq 0 ]; then #unless cancel/no
                femto-meshtasticd-config.sh -s
                dialog --no-collapse --msgbox "Meshtasticd service started/restarted." 6 45
              fi
            ;;
            "Stop service")
              dialog --no-collapse --colors --title "$title" --yesno "Stop Meshtasticd service?\n\nThis will take the node \Zu\Z1OFFLINE\Zn.\n\nMeshtasticd will automatically restart on boot if not disabled." 11 50
              if [ $? -eq 0 ]; then #unless cancel/no
                femto-meshtasticd-config.sh -t
                dialog --no-collapse --msgbox "Meshtasticd service stopped." 6 45
              fi
            ;;
            "Enable service")
              dialog --no-collapse --title "$title" --yesno "Enable Meshtasticd service?" 6 45
              if [ $? -eq 0 ]; then #unless cancel/no
                femto-meshtasticd-config.sh -M "enable"
                dialog --no-collapse --colors --msgbox "Sent \`\Zusystemctl enable meshtasticd\Zn\` and \`\Zusystemctl start meshtasticd\Zn\` commands to system.\n\nMeshtasticd should be running." 10 50
              fi
            ;;
            "Disable service")
              dialog --no-collapse --colors --title "$title" --yesno "Disable Meshtasticd service?\n\nThis will take the node \Zu\Z1OFFLINE\Zn and will not restart!" 9 50
              if [ $? -eq 0 ]; then #unless cancel/no
                femto-meshtasticd-config.sh -M "disable"
                dialog --no-collapse --colors --msgbox "Sent \`\Zusystemctl disable meshtasticd\Zn\` and \`\Zusystemctl stop meshtasticd\Zn\` commands to system.\n\nMeshtasticd is disabled and stopped." 10 50
              fi
            ;;
            "Back to previous menu") break ;; 
          esac
        done
      ;;
      8) #Upgrade meshtasticd)
        dialog --no-collapse --title "$title" --yesno "Upgrade Meshtasticd?\nRequires internet connection." 0 0
        if [ $? -eq 0 ]; then #unless cancel/no
          femto-meshtasticd-config.sh -z
          pause
        fi
      ;;
      9) #uninstall meshtasticd)
        dialog --no-collapse --colors --title "$title" --yesno "Uninstall Meshtasticd?\n\nFoxbuntu was designed with Meshtasticd integration in mind, and may behave unexpectedly if Meshtasticd is removed.\n\nThis will take the node \Zu\Z1OFFLINE\Zn and will not restart!" 0 0
        if [ $? -eq 0 ]; then
          femto-meshtasticd-config.sh -x
          dialog --no-collapse --colors --msgbox "Meshtasticd uninstalled. To purge all remnants, run \`\Zusudo apt purge\Zn\`." 8 40
        fi
      ;;
      10)
        return
      ;;
    esac
  done
}

#Help menu
help_menu() {
  while true; do
  local title="Help / About"
    help_choice=$(dialog --no-collapse --cancel-label "Back" --default-item "$help_choice" --menu "$title" 0 0 7 \
      1 "About Femtofox" \
      2 "Display pinout" \
      3 "Femtofox licensing info - short" \
      4 "Femtofox licensing info - long" \
      5 "Meshtastic licensing info" \
      6 "About Luckfox" \
      7 "About Ubuntu" \
      " " "" \
    8 "Back to main menu" 3>&1 1>&2 2>&3)
    
    exit_status=$? # This line checks the exit status of the dialog command
    if [ $exit_status -eq 1 ]; then # Exit the loop if the user selects "Cancel" or closes the dialog
      break
    fi
    
    case $help_choice in
      1) #About Femtofox)
        dialog --no-collapse --title "About Femtofox" --default-item "$choice" --backtitle "Foxbuntu $(grep -oP 'major=\K[0-9]+' /etc/foxbuntu-release).$(grep -oP 'minor=\K[0-9]+' /etc/foxbuntu-release).$(grep -oP 'patch=\K[0-9]+' /etc/foxbuntu-release)$(grep -oP 'hotfix=\K[a-z]+' /etc/foxbuntu-release)" --msgbox "$(femto-license.sh -a)" 18 65
      ;;
      2) #Display pinout)
        choice=""   # zero the choice before loading the submenu
        while true; do
          choice=$(dialog --no-collapse --cancel-label "Back" --menu "Pinouts" 15 40 5 \
            1 "Femtofox Pro/CE" \
            2 "Femtofox Zero" \
            3 "Femtofox Tiny" \
            4 "Luckfox Pico Mini" \
            " " "" \
            5 "Back to Help Menu" 3>&1 1>&2 2>&3)
          
          exit_status=$? # This line checks the exit status of the dialog command
          
          if [ $exit_status -eq 1 ]; then # Exit the loop if the user selects "Cancel" or closes the dialog
            break
          fi
          
          case $choice in
            1) dialog --no-collapse --title "Femtofox" --msgbox "$(femto-pinout.sh -f)" 43 68 ;;
            2) dialog --no-collapse --title "Femtofox Zero" --msgbox "$(femto-pinout.sh -z)" 34 48 ;;
            3) dialog --no-collapse --title "Femtofox Tiny" --msgbox "$(femto-pinout.sh -t)" 38 70 ;;
            4) dialog --no-collapse --title "Luckfox Pico Mini" --msgbox "$(femto-pinout.sh -l)" 23 65 ;;
            5) break ;;
          esac
        done
      ;;
      3) #Femtofox licensing info - short)
        dialog --no-collapse --title "Femtofox license" --msgbox "$(femto-license.sh -f)" 28 60
      ;;
      4) #Femtofox licensing info - long)
        clear
        femto-license.sh -F
        pause
      ;;
      5) #Meshtastic licensing info)
        dialog --no-collapse --title "Meshtastic license" --msgbox "$(femto-license.sh -m)" 0 0
      ;;
      6) #About Luckfox)
        dialog --no-collapse --title "About Luckfox" --msgbox "$(femto-license.sh -l)" 0 0
      ;;
      7) #About Ubuntu)
        dialog --no-collapse --title "About Ubuntu" --msgbox "$(femto-license.sh -u)" 0 0
      ;;
      8)
        return
      ;;
    esac
  done
}

# Parse options
help="If script is run without arguments, femto-config menu will load.\n\
Options are:\n\
-h           This message\n\
-l           Set LoRa radio model menu\n\
-w           Set Wi-Fi config menu\
"
while getopts ":hlwL:i" opt; do
  case ${opt} in
    h) # Option -h (help)
      echo -e $help
      ;;
    l) # Option -l (set lora radio)
      set_lora_radio
    ;;
    w) # Option -w (Wi-Fi config)
      wifi_config
    ;;
    \?) # Unknown option)
      echo -e "Unknown argument $1.\n$help"
    ;;
  esac
done
if [ -n "$1" ]; then
  exit
fi

# Main menu
while true; do
  main_menu_choice=$(dialog --no-collapse --cancel-label "Exit" --default-item "$main_menu_choice" --menu "Femtofox Config" 16 40 5 \
    1 "Settings wizard" \
    2 "Networking" \
    3 "Meshtastic" \
    4 "Software manager" \
    5 "Utilities" \
    6 "Help" \
    " " "" \
    7 "Exit" 3>&1 1>&2 2>&3)
  
  exit_status=$? # This line checks the exit status of the dialog command
  
  if [ $exit_status -eq 1 ]; then # Exit the loop if the user selects "Cancel" or closes the dialog
    break
  fi
  
  case $main_menu_choice in
    1) femto-install-wizard.sh ;;
    2) networking_settings ;;
    3) meshtastic_settings ;;
    4) femto-software.sh ;;
    5) utilities ;;
    6) help_menu ;;
    7) break ;;
  esac
done

exit 0
