#!/bin/sh

# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2009-2014 Stephan Raue (stephan@openelec.tv)
# Copyright (C) 2016-present Team LibreELEC (https://libreelec.tv)

# some DOCs:

# list devices:
# cat /proc/partitions | sed -n "s/\ *[0-9][0-9]*\ *[0-9][0-9]*\ *[0-9][0-9]*\ \([a-z]*\)$/\1/p"

# list all partitionnumbers from /dev/sda:
# parted -m /dev/sda print | grep -v ^/dev | grep -v ^BYT | cut -f1 -d ":"

# list device data from /dev/sda:
# parted -m /dev/sda print | grep /dev/sda

# list mounted partitions:
# mount | grep ^/dev

# list modelnumber:
# parted -m /dev/sda print | grep /dev/sda | cut -f7 -d ":" | sed "s/;//"
# list size:
# parted -m /dev/sda print | grep /dev/sda | cut -f2 -d ":"

# exclude mounted partitions
# for i in `cat /proc/mounts | grep ^/dev/ | cut -f1 -d " " | sed "s/[0-9]//"`; do TEST="$TEST `echo "| grep -v $i"`"; done

# disable Ctrl+C - can be very dangerous
trap '' 2

# Don't execute if installer.conf doesn't exist
[ -f /etc/installer.conf ] && . /etc/installer.conf || exit 0

# Bring in OS variables.
. /etc/os-release

# Initialize controller input
/usr/bin/control-gen_init.sh
source /storage/.config/gptokeyb/control.ini
get_controls

if [ -f "/etc/installer.gptk" ]
then
  cp /etc/installer.gptk /storage/.config/gptokeyb/installer.gptk
  ${GPTOKEYB} "installer" -c "/storage/.config/gptokeyb/installer.gptk" &
fi

dbglg() {
  # Acts just like echo cmd, with automatic redirection

  echo "" >> $LOGFILE
  echo "#################################################################" >> $LOGFILE
  echo "# $@" >> $LOGFILE
  echo "#################################################################" >> $LOGFILE
  echo "" >> $LOGFILE
}

log_system_status() {
  echo "# cat /proc/mounts"
  cat /proc/mounts
  echo

  echo "# df"
  df
  echo

  echo "# df -h"
  df -h
  echo

  echo "# parted -s -m -l"
  parted -s -m -l
  echo

  echo "# blkid"
  blkid
  echo

  echo "# UEFI (if directory exists)"
  ls -la /sys/firmware/efi
  echo

  echo "# Disk sizes (bytes)"
  grep . /sys/block/*/size
  echo
}

unmount_devices() {
  # Unmount anything we didn't boot from so we can use it.
  for DEVICE in $(mount | awk '/\/flash |\/storage |\/loop/ {next;} /^\/dev/ {print $1}')
  do
    EDEVICE=$(echo ${DEVICE} | sed "s#/#-#g")
    systemctl stop udevil-mount@${EDEVICE}.service >> $LOGFILE 2>&1
    umount $(grep "${DEVICE}" /proc/mounts 2>/dev/null | awk '{print $2}') >> $LOGFILE 2>&1
  done
}

get_device_unmount() {
  # get all unmounted devices
  # usage: get_devices_unmount
  # uses:     -
  # provides: DEVICES

  DEVICES=""
  DEVICES=$(parted -s -m -l 2>/dev/null | grep -E '^/dev/sd|^/dev/mmcblk|^/dev/nvme' | grep -E -v '.?rpmb|.?boot?' | cut -f1 -d ":")

  for i in $(cat /proc/mounts | grep -E '^/dev/sd' | cut -f1 -d " " | sed "s/[0-9].*$//"); do
    DEVICES=$(echo ${DEVICES} | sed -e "s|$i||")
  done

  for i in $(cat /proc/mounts | grep -E '^/dev/mmcblk' | cut -f1 -d " " | sed "s/p.*$//"); do
    DEVICES=$(echo ${DEVICES} | sed -e "s|$i||")
  done

  for i in $(cat /proc/mounts | grep -E '^/dev/nvme' | cut -f1 -d " " | sed "s/p.*$//"); do
    DEVICES=$(echo ${DEVICES} | sed -e "s|$i||")
  done
}

get_partition() {
  # get all partitions of a specifed device
  # usage:    get_partitions /dev/sda
  # uses:     -
  # provides: PARTITIONS

  PARTITIONS=$(parted -s -m $1 print | grep -v ^/dev | grep -v BYT | cut -f1 -d ":")
}

create_device_list() {
  # creates device list to use in menus
  # usage:    create_devices_list
  # uses:     get_device_unmount
  # provides: DEVICE_MODEL, DEVICE_SIZE, DEVICE_LIST, DEVICE_NAME,
  #           DEVICES (get_device_unmount)

  DEVICE_MODEL=""
  DEVICE_SIZE=""
  DEVICE_LIST=""
  DEVICE_NAME=""

  unmount_devices
  get_device_unmount

  if [ "${DEVICES}" = "" ]; then
    msg_no_device
    return 1
  fi

  for i in ${DEVICES}; do
    DEVICE_MODEL=$(parted -s $i -m print | grep ^$i | cut -f7 -d ":" | sed "s/;//")
    DEVICE_SIZE=$(parted -s $i -m print | grep ^$i | cut -f2 -d ":")
    DEVICE_NAME=$(echo ${DEVICE_MODEL} ${DEVICE_SIZE} | sed 's/ /_/g')
    DEVICE_LIST="${DEVICE_LIST} $i ${DEVICE_NAME}"
  done
  return 0
}

do_install_quick() {
  # show menu
  MSG_TITLE="QUICK INSTALL MENU"
  MSG_MENU="\nUse the up/down arrows to select the device you wish to install to.\n\nPlease select a device:"
  MSG_CANCEL="Back"

  create_device_list || return

  whiptail --backtitle "$BACKTITLE" --cancel-button "$MSG_CANCEL" \
    $DIALOG_OPTIONS --title "$MSG_TITLE" --menu "$MSG_MENU" 20 50 5 \
    ${DEVICE_LIST} 2> $TMPDIR/device_for_install
  [ $? -ne 0 ] && return

  # now we must do everything
  INSTALL_DEVICE=$(cat "$TMPDIR/device_for_install")
  INSTALL_DEVICE_FULL=$(echo ${DEVICE_LIST} | sed "s|.*${INSTALL_DEVICE} \([^ ]*\).*|${INSTALL_DEVICE} \1|")

  case ${INSTALL_DEVICE} in
    "/dev/mmcblk"*|"/dev/nvme"*)
      PARTID="p"
      ;;
  esac

  prompt_gpt
  prompt_backup_unpack

  # check for confirmation (twice!)
  MSG_TITLE="Confirmation before installing"
  MSG_DETAIL="\nIf you continue the contents of the target disk will be wiped out:\n\n${INSTALL_DEVICE_FULL}\n\n"
  DIALOG_OPTIONS="--defaultno"
  whiptail --backtitle "$BACKTITLE" --title "$MSG_TITLE" \
    $DIALOG_OPTIONS --yesno "$MSG_DETAIL" 0 0
  [ $? -ne 0 ] && return

  MSG_TITLE="Confirmation before installing"
  MSG_DETAIL="\nThis is last chance to abort the installation!\n\nIf you continue the target disk will be wiped out:\n\n${INSTALL_DEVICE_FULL}\n\n\n"
  DIALOG_OPTIONS="--defaultno"
  whiptail --backtitle "$BACKTITLE" --title "$MSG_TITLE" \
    $DIALOG_OPTIONS --yesno "$MSG_DETAIL" 0 0
  [ $? -ne 0 ] && return

  # start the progress bar (whiptail --gauge)
  {
    # remove all partitions
    msg_progress_install "1" "Get all partitions ${INSTALL_DEVICE}"
    get_partition ${INSTALL_DEVICE} 2>>$LOGFILE

    msg_progress_install "5" "Wiping disk ${INSTALL_DEVICE}"
    dd if=/dev/zero of=${INSTALL_DEVICE} bs=4096 count=1024 2>>$LOGFILE

    # create 2 new partitions (first $PARTSIZE_SYSTEM, second rest)
    msg_progress_install "7"  "Creating label on ${INSTALL_DEVICE}"
    if [ "$GPT" = "1" ]; then
      parted -s ${INSTALL_DEVICE} mklabel gpt >> $LOGFILE 2>&1
    else
      parted -s ${INSTALL_DEVICE} mklabel msdos >> $LOGFILE 2>&1
    fi

    case ${HW_ARCH} in
      arm|aarch64)
        if [ -e "/usr/share/bootloader/rkspi_loader.img" ]
        then
          msg_progress_install "8" "Installing Rockchip SPI Loader to ${INSTALL_DEVICE}"
          dd if=/usr/share/bootloader/rkspi_loader.img of=${INSTALL_DEVICE} conv=notrunc >> $LOGFILE 2>&1
          msg_progress_install "9" "Tell the kernel we have a new partition table on ${INSTALL_DEVICE}"
          partprobe ${INSTALL_DEVICE} >> $LOGFILE 2>&1
          printf "fix " | parted  ---pretend-input-tty ${INSTALL_DEVICE} print >> $LOGFILE 2>&1
          PART1=7
          INSTALL_UBOOT=false
        else
          PART1=1
          msg_progress_install "8"  "Creating uboot partition on ${INSTALL_DEVICE}${PARTID}${PART1}"
          parted -s "${INSTALL_DEVICE}" unit s mkpart uboot 16384 24575 >> $LOGFILE 2>&1
          if [ -e "/usr/share/bootloader/trust.img" ]
          then
            TRUST_LABEL="trust"
          elif [ -e "/usr/share/bootloader/resource.img" ]
          then
            TRUST_LABEL="resource"
          fi
          if [ -n "${TRUST_LABEL}" ]
          then
            PART1=$(( ${PART1} + 1 ))
            msg_progress_install "8"  "Creating ${TRUST_LABEL} partition on ${INSTALL_DEVICE}${PARTID}${PART1}"
            parted -s "${INSTALL_DEVICE}" unit s mkpart ${TRUST_LABEL} 24576 32767 >> $LOGFILE 2>&1
          fi
        fi
      ;;
      *)
        msg_progress_install "9" "Writing Master Boot Record on ${INSTALL_DEVICE}"
        PART1=0
        if [ "$GPT" = "1" ]; then
          cat /usr/share/syslinux/gptmbr.bin > ${INSTALL_DEVICE}
        else
          cat /usr/share/syslinux/mbr.bin > ${INSTALL_DEVICE}
        fi
      ;;
    esac

    partsize_system_start=$PARTSIZE_SYSTEM_OFFSET
    partsize_system_end=$(((PARTSIZE_SYSTEM * 1024 * 1024 / 512) + partsize_system_start - 1))
    partsize_storage_start=$((partsize_system_end + 1))
    partsize_storage_end=-1024

    PART1=$(( ${PART1} + 1 ))
    BOOT_PART=${PART1}
    
    msg_progress_install "10" "Creating flash partition on ${INSTALL_DEVICE}${PARTID}${PART1}"
    if [ "$GPT" = "1" ]; then
      parted -s ${INSTALL_DEVICE} unit s mkpart $DISKLABEL_SYSTEM fat32 -- $partsize_system_start $partsize_system_end >> $LOGFILE 2>&1
    else
      parted -s ${INSTALL_DEVICE} unit s mkpart primary fat32 -- $partsize_system_start $partsize_system_end >> $LOGFILE 2>&1
    fi

    PART2=$(( ${PART1} + 1 ))
    msg_progress_install "13" "Creating storage partition on ${INSTALL_DEVICE}${PARTID}${PART2}"
    if [ "$GPT" = "1" ]; then
      parted -s ${INSTALL_DEVICE} unit s mkpart $DISKLABEL_STORAGE ext4 -- $partsize_storage_start $partsize_storage_end >> $LOGFILE 2>&1
    else
      parted - ${INSTALL_DEVICE} unit s mkpart storage ext4 -- $partsize_storage_start $partsize_storage_end >> $LOGFILE 2>&1
    fi

    msg_progress_install "16" "Setup bootflag on partition ${BOOT_PART} of ${INSTALL_DEVICE}"
    parted -s ${INSTALL_DEVICE} set ${BOOT_PART} boot on >> $LOGFILE 2>&1

    case ${HW_ARCH} in
      i686|x86_64)
        if [ "$GPT" = "1" ]; then
          parted -s ${INSTALL_DEVICE} set ${BOOT_PART} legacy_boot on >> $LOGFILE 2>&1
        fi
      ;;
    esac

    msg_progress_install "20" "Tell the kernel we have a new partition table on ${INSTALL_DEVICE}"
    partprobe ${INSTALL_DEVICE} >> $LOGFILE 2>&1

    # create filesystem
    msg_progress_install "23" "Creating filesystem on ${INSTALL_DEVICE}1"
    mkfs.vfat ${INSTALL_DEVICE}${PARTID}${PART1} >> $LOGFILE 2>&1

    msg_progress_install "25" "Set uuid and disklabel $DISKLABEL_SYSTEM on ${INSTALL_DEVICE}${PART1}"
    dosfslabel ${INSTALL_DEVICE}${PARTID}${PART1}  $DISKLABEL_SYSTEM >> $LOGFILE 2>&1

    msg_progress_install "28" "Creating filesystem on ${INSTALL_DEVICE}${PARTID}${PART2}"
    mke2fs -t ext4 -m 0 ${INSTALL_DEVICE}${PARTID}${PART2} >> $LOGFILE 2>&1

    msg_progress_install "30" "Set uuid and disklabel $DISKLABEL_STORAGE on ${INSTALL_DEVICE}${PARTID}${PART2}"
    tune2fs -U random -L $DISKLABEL_STORAGE  ${INSTALL_DEVICE}${PARTID}${PART2} >> $LOGFILE 2>&1

    UUID_SYSTEM="$(blkid --output udev ${INSTALL_DEVICE}${PARTID}${PART1} | grep ^ID_FS_UUID= | cut -d= -f2)"
    UUID_STORAGE="$(blkid --output udev ${INSTALL_DEVICE}${PARTID}${PART2} | grep ^ID_FS_UUID= | cut -d= -f2)"

    echo "" >> $LOGFILE
    echo "UUID_SYSTEM : ${UUID_SYSTEM}" >> $LOGFILE
    echo "UUID_STORAGE: ${UUID_STORAGE}" >> $LOGFILE

    # mount system partition
    msg_progress_install "35" "Creating $TMPDIR/part1"
    mkdir -p $TMPDIR/part1 >> $LOGFILE 2>&1

    msg_progress_install "40" "Mounting ${INSTALL_DEVICE}${PART1} to $TMPDIR/part1"
    mount -t vfat ${INSTALL_DEVICE}${PARTID}${PART1} $TMPDIR/part1 >> $LOGFILE 2>&1

    case ${HW_ARCH} in
      arm|aarch64)
        if [ ! "${INSTALL_UBOOT}" = false ]
        then
          msg_progress_install "50" "Installing bootloader to $TMPDIR/part1"
          /usr/share/bootloader/update.sh "${INSTALL_DEVICE}" "${TMPDIR}/part1" "$UUID_SYSTEM" "$UUID_STORAGE" "$SYSLINUX_PARAMETERS"
          mount -o remount,rw $TMPDIR/part1
        fi
      ;;
      i686|x86_64)
        # installing syslinux
        msg_progress_install "50" "Installing syslinux to $TMPDIR/part1"
        syslinux -i ${INSTALL_DEVICE}${PARTID}${PART1} >> $LOGFILE 2>&1

        # configuring bootloader
        msg_progress_install "80" "Setup bootloader with boot label = $DISKLABEL_SYSTEM and disk label = $DISKLABEL_STORAGE"
        mkdir -p $TMPDIR/part1/EFI/BOOT
        cat << EOF > $TMPDIR/part1/syslinux.cfg
DEFAULT linux
PROMPT 0

LABEL linux
 KERNEL /KERNEL
 APPEND boot=UUID=$UUID_SYSTEM disk=UUID=$UUID_STORAGE $SYSLINUX_PARAMETERS rootwait quiet systemd.debug_shell=ttyFIQ0 earlycon=uart8250,mmio32,0xfeb50000 console=ttyFIQ0 console=tty0 coherent_pool=2M fbcon=rotate:1
EOF

        cat << EOF > $TMPDIR/part1/EFI/BOOT/grub.cfg
set timeout="0"
set default="${DISTRO}"

menuentry "${DISTRO}" {
       search --set -f /KERNEL
       linux /KERNEL boot=UUID=$UUID_SYSTEM disk=UUID=$UUID_STORAGE rootwait quiet systemd.debug_shell=ttyFIQ0 earlycon=uart8250,mmio32,0xfeb50000 console=ttyFIQ0 console=tty0 coherent_pool=2M fbcon=rotate:1
}
EOF

        # uefi boot / hybrid mode
        cp /usr/share/syslinux/bootx64.efi $TMPDIR/part1/EFI/BOOT
        cp /usr/share/syslinux/ldlinux.e64 $TMPDIR/part1/EFI/BOOT
        cp /usr/share/grub/bootia32.efi $TMPDIR/part1/EFI/BOOT
      ;;
    esac

    # install system files
    msg_progress_install "60" "Installing Kernel"
    cp "/flash/$IMAGE_KERNEL" $TMPDIR/part1/KERNEL >> $LOGFILE 2>&1

    msg_progress_install "65" "Installing System"
    cp "/flash/$IMAGE_SYSTEM" $TMPDIR/part1/SYSTEM >> $LOGFILE 2>&1
    sync

    sync

    # umount system partition, remove mountpoint
    msg_progress_install "85" "Unmount $TMPDIR/part1"
    umount $TMPDIR/part1 >> $LOGFILE 2>&1

    msg_progress_install "87" "Remove $TMPDIR/part1"
    rmdir $TMPDIR/part1 >> $LOGFILE 2>&1

    if [ "$BACKUP_UNPACK" = "1" ]; then
      # mount storage partition
      msg_progress_install "89" "Creating $TMPDIR/part2"
      mkdir -p $TMPDIR/part2 >> $LOGFILE 2>&1

      msg_progress_install "90" "Mounting ${INSTALL_DEVICE}${PARTID}${PART2} to $TMPDIR/part2"
      mount -t ext4 ${INSTALL_DEVICE}${PARTID}${PART2} $TMPDIR/part2 >> $LOGFILE 2>&1

      msg_progress_install "92" "Restoring backup"
      [ -f /flash/backup.tar.bz2 ] && tar -xjf /flash/backup.tar.bz2 -C $TMPDIR/part2 >> $LOGFILE 2>&1
      [ -f /flash/backup.zip ] && unzip -qq /flash/backup.zip -d $TMPDIR/part2 >> $LOGFILE 2>&1
      sync

      # umount system partition, remove mountpoint
      msg_progress_install "97" "Unmount $TMPDIR/part2"
      umount $TMPDIR/part2 >> $LOGFILE 2>&1

      msg_progress_install "100" "Remove $TMPDIR/part2"
      rmdir $TMPDIR/part2 >> $LOGFILE 2>&1
    fi
  } | whiptail --backtitle "$BACKTITLE" --gauge "Please wait while your system is being setup ..." 6 73 0

  # install complete
  MSG_TITLE="JELOS Install Complete"
  MSG_DETAIL="You may now remove the install media and shutdown.\n"
  whiptail --backtitle "$BACKTITLE" --title "$MSG_TITLE" --msgbox "$MSG_DETAIL" 7 73
}

msg_no_device() {
  # show a warning dialog if we dont find not mounted devices for install and return to main menu
  MSG_TITLE="WARNING"
  MSG_INFOBOX=" No devices were found. "

  whiptail --backtitle "$BACKTITLE" --title "$MSG_TITLE" --msgbox "$MSG_INFOBOX" 9 73
}

msg_progress_install() {
  # update the whiptail gauge window

  dbglg "$2"
  sleep .3
  echo XXX
  echo $1
  echo "$2 ..."
  echo XXX
}

prompt_gpt() {
  case ${HW_ARCH} in
    arm|aarch64)
      BOOT_DEVICE=$(blkid | awk 'BEGIN {FS=":"} /'$(cat /proc/cmdline | sed -e 's~^.*disk=UUID=~~g; s~\ .*$~~g')'/ {print $1}' | sed 's~p[0-9].*$~~g')
      BOOT_LABEL="$(blkid ${BOOT_DEVICE} | grep -Eo 'PTTYPE=".*"' | sed 's~PTTYPE=~~g; s~"~~g')"
      case ${BOOT_LABEL} in
        gpt)
          GPT="1"
        ;;
        *)
          GPT="0"
        ;;
      esac
      UEFI="0"
    ;;
    *)
     GPT="0"
     UEFI="0"
     # Get size in GB.
     # 2^41 bytes is the DOS limit (2199023255552 bytes, 2.2TB). Use GUID Partition Table.>= 2200GB
     INSTALL_DEVICE_SIZE=$(($(cat /sys/block/${INSTALL_DEVICE#/dev/}/size)*512/1000/1000/1000))
     if [ "${INSTALL_DEVICE_SIZE}" -ge 2200 ] 2>/dev/null; then
       GPT="1"
     fi
     # force gpt + uefi in uefi boot mode
     if [ -d /sys/firmware/efi ]; then
       UEFI="1"
       GPT="1"
     fi
    ;;
  esac
}

prompt_backup_unpack() {
  # Prompt for unpacking backup files to /storage
  # usage:    prompt_backup_unpack
  # uses:
  # provides: BACKUP_UNPACK
  BACKUP_UNPACK="0"
  if [ -f /flash/backup.tar.bz2 -o -f /flash/backup.zip ]; then
    MSG_TITLE="Restore backup files"
    MSG_DETAIL="Restore backup files to storage partition.\nFile backup.tar.bz2 or/and backup.zip exist on\ninstallation USB stick."
    DIALOG_OPTIONS="--defaultno"
    if whiptail --backtitle "$BACKTITLE" --title "$MSG_TITLE" $DIALOG_OPTIONS --yesno "$MSG_DETAIL" 0 0; then
      BACKUP_UNPACK="1"
    fi
  fi
}

menu_main() {
  # show the mainmenu
  MSG_TITLE="MAIN MENU"
  MSG_MENU="\nWelcome to JELOS installation tool! \
\n
This tool is used to copy JELOS from the installation media \
to your disk or other device. You'll be up and running in no time! \
Please note that the contents of the disk you choose will be wiped \
out during the installation. \
\n\nPlease select:"
  MSG_CANCEL="Close"

  whiptail --backtitle "$BACKTITLE" --cancel-button "$MSG_CANCEL" \
    --title "$MSG_TITLE" --menu "$MSG_MENU" 18 73 4 \
      1 "Install JELOS" \
      2 "View installation log" \
      3 "Save installation log" \
      4 "Shutdown" 2> $TMPDIR/mainmenu

  case $? in
    0)
      ITEM_MAINMENU=$(cat "$TMPDIR/mainmenu")
      case $ITEM_MAINMENU in
        1) do_install_quick;;
        2) logfile_show;;
        3) logfile_save;;
        4) do_poweroff;;
      esac
      ;;
    1|255)
      do_poweroff
      ;;
  esac
}

logfile_show() {
  whiptail --textbox "$LOGFILE" 20 73 --scrolltext --backtitle "$BACKTITLE"
}

logfile_save() {
  mount -o remount,rw /flash

  mkdir -p $(dirname $LOGBACKUP)
  cp $LOGFILE $LOGBACKUP
  sync

  mount -o remount,ro /flash

  MSG_TITLE="JELOS Log Saved"
  MSG_DETAIL="Log location: ${LOGBACKUP}\n"
  whiptail --backtitle "$BACKTITLE" --title "$MSG_TITLE" --msgbox "$MSG_DETAIL" 7 52
}

do_poweroff() {
  # powerdown on request
  clear
  sync
  poweroff -f
}

# setup needed variables
OS_VERSION=$(lsb_release)
BACKTITLE="JELOS Installer - ${OS_VERSION}"

TMPDIR="/tmp/installer"
LOGFILE="$TMPDIR/install.log"
LOGBACKUP="/flash/logs/$(date +%Y%m%d%H%M%S).log"

export COLORTERM="1"
export NEWT_COLORS="$WHIPTAIL_COLORS"

IMAGE_KERNEL="KERNEL"
IMAGE_SYSTEM="SYSTEM"
for arg in $(cat /proc/cmdline); do
  case $arg in
    BOOT_IMAGE=*)
      IMAGE_KERNEL="${arg#*=}"
      [ "${IMAGE_KERNEL:0:1}" = "/" ] && IMAGE_KERNEL="${IMAGE_KERNEL:1}"
      ;;
    SYSTEM_IMAGE=*)
      IMAGE_SYSTEM="${arg#*=}"
      [ "${IMAGE_SYSTEM:0:1}" = "/" ] && IMAGE_SYSTEM="${IMAGE_SYSTEM:1}"
      ;;
  esac
done

# prepare temporary directory
rm -rf $TMPDIR
mkdir -p $TMPDIR

#create log file
echo "JELOS Installer - ${OS_VERSION} started at:" > $LOGFILE
date >> $LOGFILE

dbglg "System status"
log_system_status >> $LOGFILE 2>&1

# generate the en_US.UTF-8 locale to enable line drawing
mkdir -p $TMPDIR/locale
echo "Please wait, configuring en_US.UTF-8."
localedef -i en_US -f UTF-8 $TMPDIR/locale/en_US.UTF-8
export LOCPATH=$TMPDIR/locale
export LC_ALL=en_US.UTF-8

# main

while true; do
  clear
  menu_main
done

kill -9 $(pidof gptokeyb) 2>/dev/null

# exit cleanly
exit 0
