#!/bin/bash

export VERSION_NAME=1.4
export VERSION_DATE=22.07.2024
export VERSION="v${VERSION_NAME}_d${VERSION_DATE}"
export CURRENT_PID=$$

export BOARD_VERSION=$(repka-control get-board-version)
export THROTTLING_PROFILE=$(repka-control get-throttling-profile)
export PINOUT=$(repka-control get-pinout)
export MAXIMUM_FREQUENCY=$(repka-control get-freq)
export JUMPER_STATUS=$(repka-control get-jumper)

BOARD_VERSION_SAVE=$BOARD_VERSION
THROTTLING_PROFILE_SAVE=$THROTTLING_PROFILE
PINOUT_SAVE=$PINOUT
MAXIMUM_FREQUENCY_SAVE=$MAXIMUM_FREQUENCY
JUMPER_STATUS_SAVE=$JUMPER_STATUS

check_need_reboot() {
  IS_SAME=true

  [ "$BOARD_VERSION" != "$BOARD_VERSION_SAVE" ] && IS_SAME=false
  [ "$THROTTLING_PROFILE" != "$THROTTLING_PROFILE_SAVE" ] && IS_SAME=false
  [ "$PINOUT" != "$PINOUT_SAVE" ] && IS_SAME=false
  [ "$MAXIMUM_FREQUENCY" != "$MAXIMUM_FREQUENCY_SAVE" ] && IS_SAME=false
  [ "$JUMPER_STATUS" != "$JUMPER_STATUS_SAVE" ] && IS_SAME=false

  if [ "$IS_SAME" = false ]; then
    if (
          whiptail \
            --title "Необходима перезагрузка" \
            --yesno "Вы внесли изменения в конфигурацию Repka Pi 3\nДля вступления изменений в силу необходимо перезагрузить устройство\nВыполнить перезагрузку?" \
            10 80) then
            echo "Перезагружаем $?."
	    reboot
      else
       return 0
      fi
  fi
}

need_reboot() {
  if (
    whiptail \
      --title "Необходима перезагрузка" \
      --yesno "Чтобы изменения вступили в силу необходимо перезагрузить Repka Pi 3\nВыполнить перезагрузку?" \
      10 80) then
        echo "Перезагружаем $?."
        reboot
  else
   return 0
  fi
}


set_interface() {
  CUSTOM_PORT=$1
  INTERFACE=$2

  repka-control set-custom-port "$1" "$2"
}

set_pinout() {
  PINOUT=$1
  repka-control set-pinout "$1"
}

set_max_freq() {
  MAXIMUM_FREQUENCY=$1
  repka-control set-freq "$1"
}

set_board_version() {
  BOARD_VERSION=$1
  repka-control set-board-version "$1"
}

set_jumper() {
  JUMPER_STATUS=$1
  repka-control set-jumper "$1"
}

set_throttling_profile() {
  THROTTLING_PROFILE=$1
  repka-control set-throttling-profile "$1"
}

jumper() {
  BREADCRUBS=$1
  J1_STATUS=$([[ "${JUMPER_STATUS}" = "true" ]] && echo "ON" || echo "OFF")
  J2_STATUS=$([[ "${JUMPER_STATUS}" = "false" ]] && echo "ON" || echo "OFF")

  RESULT=$(
    whiptail \
      --title "Repka Pi утилита для настройки (repka-config) ${VERSION}" \
      --radiolist \
      --cancel-button "Назад/Back" \
      --ok-button "Выбрать/Select" \
      "$BREADCRUBS" \
      20 100 10 \
      "J1 | Перемычка установлена" "" $J1_STATUS \
      "J2 | Перемычка отсутствует " "" $J2_STATUS \
      3>&1 1>&2 2>&3)

  RET=$?
  if [ $RET -eq 1 ]; then
    board_options "8 Board Options"
  elif [ $RET -eq 0 ]; then
    case "$RESULT" in
      J1\ *)
        set_jumper "true" \
          && set_throttling_profile "profile-ver1.4-1.6-passive" \
          && board_options "8 Board Options" ;;
      J2\ *)
        set_jumper "false"

        case "$BOARD_VERSION" in
          "1.3") set_throttling_profile "profile-ver1.3" && set_max_freq "1.368 GHz" && need_reboot ;;
          "1.4"|"1.5") set_throttling_profile "profile-ver1.4-1.6-passive" && set_max_freq "1.368 GHz" && need_reboot ;;
          *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
        esac

        board_options "8 Board Options" ;;
      *) whiptail --msgbox "Ошибка" 20 60 1 ;;
    esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1
  fi

}

select_interface() {
  if [ "$#" -ne 1 ]; then
    echo "Необходимо использовать аргумент CP с номером"
    return 1
  fi

  case "$1" in
    CP1)
      CP1_RESULT=$(repka-control get-custom-port 1)
      CP1_STATUS=$([[ "${CP1_RESULT}" = "" ]] && echo "ON" || echo "OFF")
      CP2_STATUS=$([[ "${CP1_RESULT}" = "i2c1" ]] && echo "ON" || echo "OFF")

      RESULT=$(
        whiptail \
          --title "CP1 | 3,5 Port" \
          --radiolist \
          "Выберите доступный интерфейс:" \
          --cancel-button "Назад/Back" \
          --ok-button "Выбрать/Select" \
          20 50 4 \
          "GPIO" "" ${CP1_STATUS} \
          "I2C1" "" ${CP2_STATUS} \
          3>&1 1>&2 2>&3)

      RET=$?
      if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
        custom_pinout_config "3 Interface Options/I3 Custom Pinout"
      elif [ $RET -eq 0 ]; then
        case "$RESULT" in
          "GPIO") set_interface "1" "" && custom_pinout_config "3 Interface Options/I3 Custom Pinout" ;;
          "I2C1") set_interface "1" "i2c1" && custom_pinout_config "3 Interface Options/I3 Custom Pinout" ;;
          *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
        esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1 || return 0
      fi
      ;;

    CP2)
      CP2_RESULT=$(repka-control get-custom-port 2)
      CP1_STATUS=$([[ "${CP2_RESULT}" = "" ]] && echo "ON" || echo "OFF")
      CP2_STATUS=$([[ "${CP2_RESULT}" = "s_uart" ]] && echo "ON" || echo "OFF")
      RESULT=$(
        whiptail \
          --title "CP2 | 16, 18 Port" \
          --radiolist \
          "Выберите доступный интерфейс:" \
          --cancel-button "Назад/Back" \
          --ok-button "Выбрать/Select" \
          20 50 4 \
          "GPIO" "" $CP1_STATUS \
          "S-UART" "" $CP2_STATUS \
          3>&1 1>&2 2>&3)

      RET=$?
      if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
        custom_pinout_config "3 Interface Options/I3 Custom Pinout"
      elif [ $RET -eq 0 ]; then
        case "$RESULT" in
          "GPIO") set_interface "2" "" && custom_pinout_config "3 Interface Options/I3 Custom Pinout" ;;
          "S-UART") set_interface "2" "s_uart" && custom_pinout_config "3 Interface Options/I3 Custom Pinout" ;;
          *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
        esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1 || return 0
      fi
      ;;

    CP3)
      CP3_RESULT=$(repka-control get-custom-port 3)
      CP1_STATUS=$([[ "${CP3_RESULT}" = "" ]] && echo "ON" || echo "OFF")
      CP2_STATUS=$([[ "${CP3_RESULT}" = "spi0" ]] && echo "ON" || echo "OFF")
      CP3_STATUS=$([[ "${CP3_RESULT}" = "spi0_can" ]] && echo "ON" || echo "OFF")
      RESULT=$(
        whiptail \
          --title "CP3 | 19, 21, 23, 24, 26 Port" \
          --radiolist \
          "Выберите доступный интерфейс:" \
          --cancel-button "Назад/Back" \
          --ok-button "Выбрать/Select" \
          20 50 4 \
          "GPIO" "" $CP1_STATUS \
          "SPI0" "" $CP2_STATUS \
          "SPI0(CAN)" "" $CP3_STATUS \
          3>&1 1>&2 2>&3)

      RET=$?
      if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
        custom_pinout_config "3 Interface Options/I3 Custom Pinout"
      elif [ $RET -eq 0 ]; then
        case "$RESULT" in
          "GPIO") set_interface "3" "" && custom_pinout_config "3 Interface Options/I3 Custom Pinout" ;;
          "SPI0") set_interface "3" "spi0" && custom_pinout_config "3 Interface Options/I3 Custom Pinout" ;;
          "SPI0(CAN)") set_interface "3" "spi0_can" && custom_pinout_config "3 Interface Options/I3 Custom Pinout" ;;
          *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
        esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1 || return 0
      fi
      ;;

    CP4)
      CP4_RESULT=$(repka-control get-custom-port 4)
      CP1_STATUS=$([[ "${CP4_RESULT}" = "" ]] && echo "ON" || echo "OFF")
      CP2_STATUS=$([[ "${CP4_RESULT}" = "i2c2" ]] && echo "ON" || echo "OFF")
      RESULT=$(
        whiptail \
          --title "CP4 | 27, 28 Port" \
          --radiolist \
          "Выберите доступный интерфейс:" \
          --cancel-button "Назад/Back" \
          --ok-button "Выбрать/Select" \
          20 50 4 \
          "GPIO" "" $CP1_STATUS \
          "I2C2" "" $CP2_STATUS \
          3>&1 1>&2 2>&3)

      RET=$?
      if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
        custom_pinout_config "3 Interface Options/I3 Custom Pinout"
      elif [ $RET -eq 0 ]; then
        case "$RESULT" in
          "GPIO") set_interface "4" "" && custom_pinout_config "3 Interface Options/I3 Custom Pinout" ;;
          "I2C2") set_interface "4" "i2c2" && custom_pinout_config "3 Interface Options/I3 Custom Pinout" ;;
          *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
        esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1 || return 0
      fi
      ;;

    CP5)
      CP5_RESULT=$(repka-control get-custom-port 5)
      CP1_STATUS=$([[ "${CP5_RESULT}" = "" ]] && echo "ON" || echo "OFF")
      CP2_STATUS=$([[ "${CP5_RESULT}" = "uart2" ]] && echo "ON" || echo "OFF")
      RESULT=$(
        whiptail \
          --title "CP5 | 29, 31 Port" \
          --radiolist \
          "Выберите доступный интерфейс:" \
          --cancel-button "Назад/Back" \
          --ok-button "Выбрать/Select" \
          20 50 4 \
          "GPIO" "" $CP1_STATUS \
          "UART2" "" $CP2_STATUS \
          3>&1 1>&2 2>&3)

      RET=$?
      if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
        custom_pinout_config "3 Interface Options/I3 Custom Pinout"
      elif [ $RET -eq 0 ]; then
        case "$RESULT" in
          "GPIO") set_interface "5" "" && custom_pinout_config "3 Interface Options/I3 Custom Pinout" ;;
          "UART2") set_interface "5" "uart2" && custom_pinout_config "3 Interface Options/I3 Custom Pinout" ;;
          *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
        esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1 || return 0
      fi
      ;;

    CP6)
      CP6_RESULT=$(repka-control get-custom-port 6)
      CP1_STATUS=$([[ "${CP6_RESULT}" = "" ]] && echo "ON" || echo "OFF")
      CP2_STATUS=$([[ "${CP6_RESULT}" = "pwm0" ]] && echo "ON" || echo "OFF")
      RESULT=$(
        whiptail \
          --title "CP6 | 33 Port" \
          --radiolist \
          "Выберите доступный интерфейс:" \
          --cancel-button "Назад/Back" \
          --ok-button "Выбрать/Select" \
          20 50 4 \
          "GPIO" "" $CP1_STATUS \
          "PWM0" "" $CP2_STATUS \
          3>&1 1>&2 2>&3)

      RET=$?
      if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
        custom_pinout_config "3 Interface Options/I3 Custom Pinout"
      elif [ $RET -eq 0 ]; then
        case "$RESULT" in
          "GPIO") set_interface "6" "" && custom_pinout_config "3 Interface Options/I3 Custom Pinout" ;;
          "PWM0") set_interface "6" "pwm0" && custom_pinout_config "3 Interface Options/I3 Custom Pinout" ;;
          *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
        esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1 || return 0
      fi
      ;;

    CP7)
      CP7_RESULT=$(repka-control get-custom-port 7)
      CP1_STATUS=$([[ "${CP7_RESULT}" = "" ]] && echo "ON" || echo "OFF")
      CP2_STATUS=$([[ "${CP7_RESULT}" = "spi1" ]] && echo "ON" || echo "OFF")
      CP3_STATUS=$([[ "${CP7_RESULT}" = "i2s" ]] && echo "ON" || echo "OFF")
      CP4_STATUS=$([[ "${CP7_RESULT}" = "i2s_pcm5122" ]] && echo "ON" || echo "OFF")
      RESULT=$(
        whiptail \
          --title "CP7 | 12, 35, 36, 38, 40 Port" \
          --radiolist \
          "Выберите доступный интерфейс:" \
          --cancel-button "Назад/Back" \
          --ok-button "Выбрать/Select" \
          20 50 4 \
          "GPIO" "" $CP1_STATUS \
          "SPI1" "" $CP2_STATUS \
          "I2S" "" $CP3_STATUS \
          "I2S-PCM5122" "" $CP4_STATUS \
          3>&1 1>&2 2>&3)

      RET=$?
      if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
        custom_pinout_config "3 Interface Options/I3 Custom Pinout"
      elif [ $RET -eq 0 ]; then
        case "$RESULT" in
          "GPIO") set_interface "7" "" && custom_pinout_config "3 Interface Options/I3 Custom Pinout" ;;
          "SPI1") set_interface "7" "spi1" && custom_pinout_config "3 Interface Options/I3 Custom Pinout" ;;
          "I2S") set_interface "7" "i2s" && custom_pinout_config "3 Interface Options/I3 Custom Pinout" ;;
          "I2S-PCM5122") set_interface "7" "i2s_pcm5122" && custom_pinout_config "3 Interface Options/I3 Custom Pinout" ;;
          *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
        esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1 || return 0
      fi
      ;;
    *)
        echo "Invalid argument: $1"
        return 1
        ;;
  esac
}

custom_pinout_config() {
  BREADCRUBS=$1
  CP1="$(repka-control get-custom-port 1)"
  CP2="$(repka-control get-custom-port 2)"
  CP3="$(repka-control get-custom-port 3)"
  CP4="$(repka-control get-custom-port 4)"
  CP5="$(repka-control get-custom-port 5)"
  CP6="$(repka-control get-custom-port 6)"
  CP7="$(repka-control get-custom-port 7)"

  RESULT=$(
      whiptail \
        --title "Repka Pi утилита для настройки (repka-config) ${VERSION}"  \
        --menu "$BREADCRUBS \n\nВыберите нужный набор пинов для установки конкретного интерфейса:" \
        20 80 10 \
        --cancel-button "Выйти/Finish" \
        --ok-button "Выбрать/Select" \
        "3, 5 Pins" "  - $(if [ -z "$CP1" ]; then echo '[GPIO]'; else echo 'GPIO'; fi)/$(if [ $CP1 = "i2c1" ]; then echo '[I2C1]'; else echo 'I2C1'; fi)" \
        "16, 18 Pins" "  - $(if [ -z "$CP2" ]; then echo '[GPIO]'; else echo 'GPIO'; fi)/$(if [ $CP2 = "s_uart" ]; then echo '[S-UART]'; else echo 'S-UART'; fi)" \
        "19, 21, 23, 24, 26 Pins" "  - $(if [ -z "$CP3" ]; then echo '[GPIO]'; else echo 'GPIO'; fi)/$(if [ $CP3 = "spi0" ]; then echo '[SPI0]'; else echo 'SPI0'; fi)/$(if [ $CP3 = "spi0_can" ]; then echo '[SPI0(CAN)]'; else echo 'SPI0(CAN)'; fi)" \
        "27, 28 Pins" "  - $(if [ -z "$CP4" ]; then echo '[GPIO]'; else echo 'GPIO'; fi)/$(if [ $CP4 = "i2c2" ]; then echo '[I2C2]'; else echo 'I2C2'; fi)" \
        "29, 31 Pins" "  - $(if [ -z "$CP5" ]; then echo '[GPIO]'; else echo 'GPIO'; fi)/$(if [ $CP5 = "uart2" ]; then echo '[UART2]'; else echo 'UART2'; fi)" \
        "33 Pins" "  - $(if [ -z "$CP6" ]; then echo '[GPIO]'; else echo 'GPIO'; fi)/$(if [ $CP6 = "pwm0" ]; then echo '[PWM0]'; else echo 'PWM0'; fi)" \
        "12, 35, 36, 38, 40 Pins" "  - $(if [ -z "$CP7" ]; then echo '[GPIO]'; else echo 'GPIO'; fi)/$(if [ $CP7 = "spi1" ]; then echo '[SPI1]'; else echo 'SPI1'; fi)/$(if [ $CP7 = "i2s" ]; then echo '[I2S]'; else echo 'I2S'; fi)/$(if [ $CP7 = "i2s_pcm5122" ]; then echo '[I2S-PCM5122]'; else echo 'I2S-PCM5122'; fi)" \
        3>&1 1>&2 2>&3)

  RET=$?
  if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
    interface_options "3 Interface Options"
  elif [ $RET -eq 0 ]; then
    case "$RESULT" in
      "3, 5 Pins") select_interface "CP1" ;;
      "16, 18 Pins") select_interface "CP2" ;;
      "19, 21, 23, 24, 26 Pins") select_interface "CP3" ;;
      "27, 28 Pins") select_interface "CP4" ;;
      "29, 31 Pins") select_interface "CP5" ;;
      "33 Pins") select_interface "CP6" ;;
      "12, 35, 36, 38, 40 Pins") select_interface "CP7" ;;
      *) whiptail --msgbox "Ошибка" 20 60 1 ;;
    esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1
  fi
}

board_version() {
  BREADCRUBS=$1
  VB1_STATUS=$([[ ${BOARD_VERSION} = "1.3" ]] && echo "ON" || echo "OFF")
  VB2_STATUS=$([[ ${BOARD_VERSION} = "1.4" ]] && echo "ON" || echo "OFF")
  VB3_STATUS=$([[ ${BOARD_VERSION} = "1.5" ]] && echo "ON" || echo "OFF")
  VB4_STATUS=$([[ ${BOARD_VERSION} = "1.6" ]] && echo "ON" || echo "OFF")

  RESULT=$(
    whiptail \
      --title "Repka Pi утилита для настройки (repka-config) ${VERSION}" \
      --radiolist \
      --cancel-button "Назад/Back" \
      --ok-button "Выбрать/Select" \
      "$BREADCRUBS" \
      20 100 10 \
      "VB1 | ver 1.3 и младше" "Доступна максимальная частота процессора: 1008/1200/1368GHz" $VB1_STATUS \
      "VB2 | ver 1.4 " "Доступна максимальная частота процессора: 1368GHz" $VB2_STATUS \
      "VB3 | ver 1.5 " "Доступна максимальная частота процессора: 1368GHz" $VB3_STATUS \
      "VB4 | ver 1.6" "Доступна максимальная частота процессора: 1416GHz" $VB4_STATUS \
      3>&1 1>&2 2>&3)

  RET=$?
  if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
    board_options "8 Board Options"
  elif [ $RET -eq 0 ]; then
    case "$RESULT" in
      VB1\ *)
        set_board_version "1.3" \
          && set_max_freq "1.368 GHz" \
          && set_throttling_profile "profile-ver1.3"

        if [ "$PINOUT" = "7" ] || [ "$PINOUT" = "8" ]; then
          set_pinout 1
        fi

        need_reboot
        board_options "8 Board Options" ;;
      VB2\ *)
        set_board_version "1.4" \
          && set_max_freq "1.368 GHz" \
          && set_throttling_profile "profile-ver1.4-1.6-passive"

        if [ "$PINOUT" = "7" ] || [ "$PINOUT" = "8" ]; then
          set_pinout 1
        fi

        need_reboot
        board_options "8 Board Options" ;;
      VB3\ *)
        set_board_version "1.5" \
          && set_max_freq "1.368 GHz" \
          && set_throttling_profile "profile-ver1.4-1.6-passive"

        if [ "$PINOUT" = "7" ] || [ "$PINOUT" = "8" ]; then
          set_pinout 1
        fi

        need_reboot
        board_options "8 Board Options" ;;
      VB4\ *)
        set_board_version "1.6" \
          && set_max_freq "1.416 GHz" \
          && set_throttling_profile "profile-ver1.4-1.6-passive" \
          && need_reboot \
          && board_options "8 Board Options" ;;
      *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
    esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1 || return 0
  fi
}

set_debug_uart_status() {
  STATUS=$1

  if [ ${STATUS} -eq 0 ]; then
    cp /boot/boot-tty6.scr /boot/boot.scr
    dd if=/boot/spl/u-boot-sunxi-with-spl-dram-672-nottys0.bin of=/dev/mmcblk0 bs=1024 seek=8 conv=notrunc
  else
    cp /boot/boot-ttyS0.scr /boot/boot.scr
    dd if=/boot/spl/u-boot-sunxi-with-spl-dram-672.bin of=/dev/mmcblk0 bs=1024 seek=8 conv=notrunc
  fi
}

Ubuntu_update() {
  apt-get update &&
  apt-get upgrade &&
  printf "Ожидаем 5 секунд до повторного запуска repka-config\n" &&
  sleep 5 &&
  exec repka-config
}

Repka_OS_update() {
  export REPKA_OS_UPDATE=/usr/local/repka-os-update
  wget -O $REPKA_OS_UPDATE --timeout=120 https://download.repka-pi.ru/repka_os_update/repka-os-update
  chmod +x $REPKA_OS_UPDATE
  $REPKA_OS_UPDATE
  rm $REPKA_OS_UPDATE
}

repka_config_update() {
  wget -qO - https://download.repka-pi.ru/repka-tools/repka-config/repka-config-update.sh | bash -s $CURRENT_PID
  return 0
}

# S1 Select-kernel
select_kernel () {
  wget -O - https://download.repka-pi.ru/kernel/kernel-update.sh | bash
  return 0
}

# S2 GUI / Console
gui_console() {
  BREADCRUBS="$1/"
  RESULT=$(
    whiptail \
    --title "Режим запуска операционной системы" \
    --menu "$BREADCRUBS" \
    20 80 8 \
	  "1 GUI" "  - Графический режим, работа в графическом окружении " \
	  "2 Console" "  - Консольный режим, работа в коммандной строке " \
	  3>&1 1>&2 2>&3)

  RET=$?
  if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
    return 0
  elif [ $RET -eq 0 ]; then
    case "$RESULT" in
      1\ *) systemctl set-default graphical.target && need_reboot ;;
      2\ *) systemctl set-default multi-user.target && need_reboot ;;
      *) whiptail --msgbox "Ошибка" 20 60 1 ;;
    esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1
  fi
}

# S3 NetworkManager
networkmanager() {
  nmtui && return 0
}

# I1 Debug UART0
debug_UART0() {
  BREADCRUBS=$1
  RESULT=$(
    whiptail \
      --title "Repka Pi утилита для настройки (repka-config) ${VERSION}" \
      --menu "$BREADCRUBS" \
      20 80 8 \
      --cancel-button "Назад/Back" \
      --ok-button "Выбрать/Select" \
	    "debug-UART0-off " "Отключить вывод отладочных сообщений на UART0" \
	    "debug-UART0-on " "Включить вывод отладочных сообщений на UART0" \
      3>&1 1>&2 2>&3)

  RET=$?
  if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
    interface_options "3 Interface Options"
  elif [ $RET -eq 0 ]; then
    case "$RESULT" in
      debug-UART0-off\ *) set_debug_uart_status 0 && need_reboot ;;
      debug-UART0-on\ *) set_debug_uart_status 1 && need_reboot ;;
      *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
    esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1 || return 0
  fi
}

# I2 Pinout Options
pinout_options() {
  BREADCRUBS=$1
  CURRENT_PINOUT=$(repka-control get-pinout)

  PINOUT_1=$([[ "${CURRENT_PINOUT}" = "1" ]] && echo "ON" || echo "OFF")
  PINOUT_2=$([[ "${CURRENT_PINOUT}" = "2" ]] && echo "ON" || echo "OFF")
  PINOUT_3=$([[ "${CURRENT_PINOUT}" = "3" ]] && echo "ON" || echo "OFF")
  PINOUT_4=$([[ "${CURRENT_PINOUT}" = "4" ]] && echo "ON" || echo "OFF")
  PINOUT_5=$([[ "${CURRENT_PINOUT}" = "5" ]] && echo "ON" || echo "OFF")
  PINOUT_6=$([[ "${CURRENT_PINOUT}" = "6" ]] && echo "ON" || echo "OFF")
  PINOUT_7=$([[ "${CURRENT_PINOUT}" = "7" ]] && echo "ON" || echo "OFF")
  PINOUT_8=$([[ "${CURRENT_PINOUT}" = "8" ]] && echo "ON" || echo "OFF")
  PINOUT_CUSTOM=$([[ "${CURRENT_PINOUT}" = "custom" ]] && echo "ON" || echo "OFF")

  if [ ${BOARD_VERSION} = "1.6" ]; then
    OPTION_F1=$(
      whiptail \
        --title "Выбор распиновки" \
        --radiolist "$BREADCRUBS \n\nВыберите вариант распиновки портов Repka Pi:" \
        20 85 10 \
        --cancel-button "Назад/Back" \
        --ok-button "Выбрать/Select"\
        "1 Вариант" "  - GPIO-26, UART-1 (По умолчанию) " $PINOUT_1 \
        "2 Вариант" "  - GPIO-15, UART-1, SPI-2, I2C-1 " $PINOUT_2 \
        "3 Вариант" "  - GPIO-11, UART-3, SPI-2, I2C-1 " $PINOUT_3 \
        "4 Вариант" "  - GPIO-13, UART-1, SPI-2, I2C-2 " $PINOUT_4 \
        "5 Вариант" "  - GPIO-14, UART-1, SPI-2, I2C-1, PWM-1 " $PINOUT_5 \
        "6 Вариант" "  - GPIO-11, UART-3, SPI-1, I2C-1, CAN-Внешний модуль " $PINOUT_6 \
        "7 Вариант" "  - GPIO-20, UART-1, I2C-1, I2S " $PINOUT_7 \
        "8 Вариант" "  - GPIO-20, UART-1, I2C-1, I2S-PCM5122 " $PINOUT_8 \
        "9 Свой вариант" " - Выберите необходимые для вас интерфейсы " $PINOUT_CUSTOM \
        3>&1 1>&2 2>&3)

    RET=$?
    if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
      interface_options "3 Interface Options"
    elif [ $RET -eq 0 ]; then
      case "$OPTION_F1" in
    1\ *) set_pinout 1 && need_reboot ;;
    2\ *) set_pinout 2 && need_reboot ;;
    3\ *) set_pinout 3 && need_reboot ;;
    4\ *) set_pinout 4 && need_reboot ;;
    5\ *) set_pinout 5 && need_reboot ;;
    6\ *) set_pinout 6 && need_reboot ;;
    7\ *) set_pinout 7 && need_reboot ;;
    8\ *) set_pinout 8 && need_reboot ;;
    9\ *) set_pinout "custom" && need_reboot ;;
        *) whiptail --msgbox "Ошибка" 20 60 1 ;;
      esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1
    fi
  else
    OPTION_F1=$(
      whiptail \
        --title "Выбор распиновки" \
        --radiolist \
        "$BREADCRUBS \n\nВыберите вариант распиновки портов Repka Pi:" \
        20 85 10 \
        --cancel-button "Назад/Back" \
        --ok-button "Выбрать/Select"\
        "1 Вариант" "  - GPIO-26, UART-1 (По умолчанию) " $PINOUT_1 \
        "2 Вариант" "  - GPIO-15, UART-1, SPI-2, I2C-1 " $PINOUT_2 \
        "3 Вариант" "  - GPIO-11, UART-3, SPI-2, I2C-1 " $PINOUT_3 \
        "4 Вариант" "  - GPIO-13, UART-1, SPI-2, I2C-2 " $PINOUT_4 \
        "5 Вариант" "  - GPIO-14, UART-1, SPI-2, I2C-1, PWM-1 " $PINOUT_5 \
        "6 Вариант" "  - GPIO-11, UART-3, SPI-1, I2C-1, CAN-Внешний модуль " $PINOUT_6 \
        "7 Свой вариант" " - Выберите необходимые для вас интерфейсы " $PINOUT_CUSTOM \
        3>&1 1>&2 2>&3)

    RET=$?
    if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
      interface_options "3 Interface Options"
    elif [ $RET -eq 0 ]; then
      case "$OPTION_F1" in
    1\ *) set_pinout 1 && need_reboot ;;
    2\ *) set_pinout 2 && need_reboot ;;
    3\ *) set_pinout 3 && need_reboot ;;
    4\ *) set_pinout 4 && need_reboot ;;
    5\ *) set_pinout 5 && need_reboot ;;
    6\ *) set_pinout 6 && need_reboot ;;
    7\ *) set_pinout "custom" && need_reboot ;;
        *) whiptail --msgbox "Ошибка" 20 60 1 ;;
      esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1
    fi
  fi
}

# P2 Maximum Frequency
max_freq() {
  BREADCRUBS=$1
  FREQ_STATUS_1=$([[ "${MAXIMUM_FREQUENCY}" = "1.008 GHz" ]] && echo "ON" || echo "OFF")
  FREQ_STATUS_2=$([[ "${MAXIMUM_FREQUENCY}" = "1.200 GHz" ]] && echo "ON" || echo "OFF")
  FREQ_STATUS_3=$([[ "${MAXIMUM_FREQUENCY}" = "1.368 GHz" ]] && echo "ON" || echo "OFF")
  FREQ_STATUS_4=$([[ "${MAXIMUM_FREQUENCY}" = "1.416 GHz" ]] && echo "ON" || echo "OFF")

  case "$BOARD_VERSION $JUMPER_STATUS" in
    "1.3 false")
      RESULT=$(
        whiptail \
          --title "Максимальная частота процессора" \
          --radiolist \
          "$BREADCRUBS \n\nВыберите максимальную частоту процессора:" \
          20 60 5 \
          "1.008 GHz" "" $FREQ_STATUS_1 \
          "1.200 GHz" "" $FREQ_STATUS_2 \
          "1.368 GHz" "" $FREQ_STATUS_3 \
          3>&1 1>&2 2>&3)
          ;;
    "1.3 true")
      RESULT=$(
        whiptail \
          --title "Максимальная частота процессора" \
          --radiolist \
          "$BREADCRUBS \n\nВыберите максимальную частоту процессора:" \
          20 60 5 \
          "1.008 GHz" "" $FREQ_STATUS_1 \
          "1.200 GHz" "" $FREQ_STATUS_2 \
          "1.368 GHz" "" $FREQ_STATUS_3 \
          "1.416 GHz" "" $FREQ_STATUS_4 \
          3>&1 1>&2 2>&3)
          ;;
    "1.4 false"|"1.5 false")
      RESULT=$(
        whiptail \
          --title  "Максимальная частота процессора" \
          --radiolist \
          "$BREADCRUBS \n\nВыберите максимальную частоту процессора:" \
          20 60 5 \
          "1.368 GHz" "" $FREQ_STATUS_3 \
          3>&1 1>&2 2>&3)
        ;;
    "1.4 true"|"1.5 true")
      RESULT=$(
        whiptail \
          --title  "Максимальная частота процессора" \
          --radiolist \
          "$BREADCRUBS \n\nВыберите максимальную частоту процессора:" \
          20 60 5 \
          "1.368 GHz" "" $FREQ_STATUS_3 \
          "1.416 GHz" "" $FREQ_STATUS_4 \
          3>&1 1>&2 2>&3)
        ;;
    "1.6 false"|"1.6 true")
      RESULT=$(
      whiptail \
        --title  "Максимальная частота процессора" \
        --radiolist \
        "$BREADCRUBS \n\nВыберите максимальную частоту процессора:" \
        20 60 5 \
        "1.416 GHz" "" $FREQ_STATUS_4 \
        3>&1 1>&2 2>&3)
      ;;
    *)
      echo "Invalid board version: $BOARD_VERSION"
      return 1
      ;;
  esac

  RET=$?
  if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
    performance_options "4 Performance Options"
  elif [ $RET -eq 0 ]; then
    case "$RESULT" in
      1.008\ *) set_max_freq "1.008 GHz" && need_reboot && performance_options "4 Performance Options" ;;
      1.200\ *) set_max_freq "1.200 GHz" && need_reboot && performance_options "4 Performance Options" ;;
      1.368\ *) set_max_freq "1.368 GHz" && need_reboot && performance_options "4 Performance Options" ;;
      1.416\ *) set_max_freq "1.416 GHz" && need_reboot && performance_options "4 Performance Options" ;;
      *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
    esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1 || return 0
  fi
  }


# B2 Cooling
cooling() {
  BREADCRUBS=$1
  C_RESULT=$(repka-control get-throttling-profile)
  CP1_STATUS=$([[ "${C_RESULT}" = "profile-ver1.3" ]] && echo "ON" || echo "OFF")
  CP2_STATUS=$([[ "${C_RESULT}" = "profile-ver1.4-1.6-passive" ]] && echo "ON" || echo "OFF")
  CP3_STATUS=$([[ "${C_RESULT}" = "profile-ver1.4-1.6-active" ]] && echo "ON" || echo "OFF")

  case "$BOARD_VERSION $JUMPER_STATUS" in
    "1.3 false")
      RESULT=$(
        whiptail \
          --title "Тип охлаждения" \
          --radiolist \
          --cancel-button "Назад/Back" \
          --ok-button "Выбрать/Select" \
          "$BREADCRUBS\n\nВыберите тип охлаждения:" \
          15 60 4 \
          "C1 | Пассивное охлаждение" "" $CP1_STATUS \
          3>&1 1>&2 2>&3) ;;
    *)
      RESULT=$(
        whiptail \
          --title "Тип охлаждения" \
          --radiolist \
          --cancel-button "Назад/Back" \
          --ok-button "Выбрать/Select" \
          "$BREADCRUBS\n\nВыберите тип охлаждения:" \
          15 60 4 \
          "C1 | Пассивное охлаждение" "" $CP2_STATUS \
          "C2 | Активное охлаждения" "" $CP3_STATUS \
          3>&1 1>&2 2>&3) ;;
  esac

  RET=$?
  if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
   performance_options "4 Performance Options"
  elif [ $RET -eq 0 ]; then
    case "$RESULT" in
      C1\ *) ([[ "${C_RESULT}" = "profile-ver1.3" ]] && set_throttling_profile "profile-ver1.3" || set_throttling_profile "profile-ver1.4-1.6-passive") && need_reboot && performance_options "4 Performance Options" ;;
      C2\ *) set_throttling_profile "profile-ver1.4-1.6-active" && need_reboot && performance_options "4 Performance Options" ;;
      *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
    esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1 || return 0
  fi
}

# 1 System Options
system_options() {
  BREADCRUBS="$1/"
  RESULT=$(
    whiptail \
      --title "Repka Pi утилита для настройки (repka-config) ${VERSION}" \
      --menu "$BREADCRUBS" \
      20 80 10 \
      --cancel-button "Назад/Back"\
      --ok-button "Выбрать/Select" \
  	  "S1 Select-kernel " "Выбрать ядро Linux" \
  	  "S2 GUI / Console " "Графическая оболочка или консоль" \
  	  "S3 NetworkManager " "Настройка сети" \
      3>&1 1>&2 2>&3)

    RET=$?

    if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
      return 0
    elif [ $RET -eq 0 ]; then
      case "$RESULT" in
        S1\ *) select_kernel ;;
        S2\ *) gui_console "${BREADCRUBS}S2 GUI\Console" ;;
        S3\ *) networkmanager ;;
        *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
      esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1 || return 0
    fi
}

# 3 Interface Options
interface_options() {
  BREADCRUBS="$1/"
  RESULT=$(
    whiptail \
    --title "Repka Pi утилита для настройки (repka-config) ${VERSION}" \
    --menu "$BREADCRUBS" \
    20 80 10 \
    --cancel-button "Назад/Back" \
    --ok-button "Выбрать/Select" \
  	"I1 Debug UART0 " "Вывод отладочных сообщений" \
  	"I2 Pinout Options" "Выбор распиновки" \
  	"I3 Custom Pinout" "Настройка своего варианта распиновки" \
    3>&1 1>&2 2>&3)

    RET=$?

    if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
      return 0
    elif [ $RET -eq 0 ]; then
      case "$RESULT" in
        I1\ *) debug_UART0 "${BREADCRUBS}I1 Debug UART0 " ;;
        I2\ *) pinout_options "${BREADCRUBS}I2 Pinout Options" ;;
        I3\ *) custom_pinout_config "${BREADCRUBS}I3 Custom Pinout" ;;
        *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
      esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1 || return 0
    fi
}

# 4 Performance Options
performance_options() {
  BREADCRUBS="$1/"
  RESULT=$(
    whiptail \
      --title "Repka Pi утилита для настройки (repka-config) ${VERSION}" \
      --menu "$BREADCRUBS" \
      20 80 10 \
      --cancel-button "Назад/Back" \
      --ok-button "Выбрать/Select" \
  	  "P1 Overclocking " "Настройка тактовых частот" \
  	  "P2 Maximum Frequency " "Максимальная частота процессора" \
  	  "P3 Cooling " "Тип охлаждения" \
      3>&1 1>&2 2>&3)

    RET=$?
    if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
      return 0
    elif [ $RET -eq 0 ]; then
      case "$RESULT" in
        P1\ *) overclocking ;;
        P2\ *) max_freq "${BREADCRUBS}P2 Maximum Frequency";;
        P3\ *) cooling "${BREADCRUBS}P3 Cooling";;
        *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
      esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1 || return 0
    fi
}

# 7 Update
update() {
  BREADCRUBS="$1/"
  echo " А есть ли интернет....хм... ? "
  if ping -c 1 repka-pi.ru > /dev/null 2>&1; then
    echo " ура интернет ^___^ "

    RESULT=$(
      whiptail \
        --title "Repka Pi утилита для настройки (repka-config) ${VERSION}" \
        --menu "$BREADCRUBS" \
        20 80 10 \
        --cancel-button "Назад/Back" \
        --ok-button "Выбрать/Select" \
        "U1 Ubuntu update pkg " "Обновить пакеты Ubuntu" \
        "U2 Repka OS update " "Обновить файлы Repka-OS" \
        "U3 repka-config update " "Обновить утилиту repka-config" \
        3>&1 1>&2 2>&3)

    RET=$?

    if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
      return 0
    elif [ $RET -eq 0 ]; then
      case "$RESULT" in
        U1\ *) Ubuntu_update ;;
        U2\ *) Repka_OS_update ;;
        U3\ *) repka_config_update ;;
        *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
      esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1 || return 0
    fi
  else
    whiptail --msgbox "Отсутствует подключение к интернету  " 10 40 1 || return 0
  fi
}

# 8 Board Options
board_options() {
  BREADCRUBS="$1/"
  if [ ${BOARD_VERSION} = "1.6" ]; then
    RESULT=$(
      whiptail \
        --title "Repka Pi утилита для настройки (repka-config) ${VERSION}" \
        --menu \
        "$BREADCRUBS" \
        20 80 10 \
        --cancel-button "Назад/Back" \
        --ok-button "Выбрать/Select" \
        "B1 Board Version " "Указать версию платы Repka Pi" \
        3>&1 1>&2 2>&3)

        RET=$?
        if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
          return 0
        elif [ $RET -eq 0 ]; then
          case "$RESULT" in
            B1\ *) board_version "${BREADCRUBS}B1 Board Version" ;;
            *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
          esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1 || return 0
        fi

  else
    RESULT=$(
      whiptail \
        --title "Repka Pi утилита для настройки (repka-config) ${VERSION}" \
        --menu "$BREADCRUBS" 20 80 10 \
        --cancel-button "Назад/Back" \
        --ok-button "Выбрать/Select" \
        "B1 Board Version " "Указать версию платы Repka Pi" \
        "B2 Jumper " "Наличие перемычки" \
        3>&1 1>&2 2>&3)

      RET=$?

      if [ $RET -eq 1 ] || [ $RET -eq 255 ]; then
        return 0
      elif [ $RET -eq 0 ]; then
        case "$RESULT" in
          B1\ *) board_version "${BREADCRUBS}B1 Board Version" ;;
          B2\ *) jumper "${BREADCRUBS}B2 Jumper" ;;
          *) whiptail --msgbox "Ошибка" 20 60 1 || return 0;;
        esac || whiptail --msgbox "Что то тут не так $RESULT" 20 60 1 || return 0
      fi
  fi
}

# 9 About repka-config
about() {
  if (
    whiptail \
      --title  "Repka Pi утилита для настройки (repka-config) ${VERSION}" \
      --yes-button  "История версий Repka OS" \
      --no-button  "Назад/Back" \
      --yesno \
      "Утилита Repka-config для удобной настройки основных функций одноплатного компьютера Repka-Pi.\nТекущая версия repka-config: ${VERSION}" \
      20 100 1); then
        xdg-open https://repka-pi.ru/project_documentation/repka-os-version/ > /dev/null 2>&1 &
        return 0
  else
       return 0
  fi
}

# Стартовый экран (появляется при запуске repka-config)
MAXIMUM_FREQUENCY_TEXT="Максимальная тактовая частота процессора (MHz): $(lscpu | grep "max MHz" | awk '{print $4}')"
RAM_TEXT="Объем оперативной памяти (МБ): $(grep MemTotal /proc/meminfo | awk '{print $2 / 1024}')"
whiptail \
  --title "Текущая максимальная частота и объем оперативной памяти"\
  --msgbox "${MAXIMUM_FREQUENCY_TEXT}\n${RAM_TEXT}"\
  0 0

# Основной цикл утилиты настройки с главным меню
while true; do
  RESULT=$(
    whiptail \
      --title "Repka Pi утилита для настройки (repka-config) ${VERSION}"  \
      --menu "Выберите настраиваемую опцию. (Для выхода из repka-config нажмите ESC)" \
      20 80 10 \
      --cancel-button "Выйти/Finish" \
      --ok-button "Выбрать/Select" \
      "1 System Options" "Системные настройки ОС" \
      "2 Display Options" "Настройка параметров дисплея" \
      "3 Interface Options" "Настройка подключения интерфейсов" \
      "4 Performance Options" "Настройка производительности" \
      "5 Localization Options" "Настройка региона и языка" \
      "6 Advanced Options" "Продвинутые настройки Repka OS" \
      "7 Update" "Обновление компонентов Repka OS" \
      "8 Board Options" "Параметры платы Repka Pi" \
      "9 About repka-config" "Информация по утилите настройки" \
      3>&1 1>&2 2>&3)

  RET=$?
  if [ $RET -eq 1 ]; then
    exit
    return 0
  elif [ $RET -eq 0 ]; then
    case "$RESULT" in
      1\ *) system_options "1 System Options" ;;
      2\ *) display_options "2 Display Options" ;;
      3\ *) interface_options "3 Interface Options" ;;
      4\ *) performance_options "4 Performance Options" ;;
      5\ *) localization_options "5 Localization Options" ;;
      6\ *) advanced_options "6 Advanced Options" ;;
      7\ *) update "7 Update" ;;
      8\ *) board_options "8 Board Options" ;;
      9\ *) about ;;
      *) whiptail --msgbox "Ой" 20 60 1 ;;
    esac || whiptail --msgbox "В разработке $RESULT" 20 60 1
  else
    check_need_reboot
    exit 1
  fi
done
