#!/bin/bash

LIB_DIR=/usr/lib/shell
loc_lib=./lib
test -e $loc_lib/lib-screen.sh && LIB_DIR=$loc_lib
. $LIB_DIR/lib-menu.sh

export TEXTDOMAIN="antiX-cli-cc"

PATH=./bin:$PATH

PLAY_LIST=/usr/share/antiX-cli-cc/Audio/Classical.m3u
BOOKMARKS=/usr/share/antiX-cli-cc/Html/bookmarks.html

YT_DEMO="https://www.youtube.com/watch?v=G8Aw2zzBE-g"   # antiX-16
YT_DEMO="https://www.youtube.com/watch?v=SghuUOPRi00"   # Removing the Swastikas

YT_DEMO_0="https://www.youtube.com/watch?v=YJg02ivYzSs" # Hyper-Reality
YT_DEMO_1="https://www.youtube.com/watch?v=njj6geeCOds" # antiX core install I
YT_DEMO_2="https://www.youtube.com/watch?v=aAYaF2Hp8Yc" # antiX core install I
YT_DEMO_3="https://www.youtube.com/watch?v=kTnR90OkNtM" # antiX core install I

YT_DEMO_NUM=4

WALLPAPER_DIR=/usr/share/wallpaper

main() {
    set_color_scheme light

    test -d /etc/live/bin && PATH=$PATH:/etc/live/bin

    clear
    #echo  -n "${cyan}Please wait while $ME examines your system ..."

    local start_t=$(get_time)

    screen_set title1=$"antiX Command-Line Control Centre"
    screen_set title2=$"Press: <Enter> to select an option, <b> back to main, <q> to quit, <h> for help"
    screen_set title3="$(distro_version)"

    screen_set box=-s border=1

    which toram_eject &>/dev/null && toram_eject --cli

    start_menu_list  # Just in case I forget elsewhere

    local start_str="init took: $(delta_time $start_t) seconds"
    log "$start_str"

    hide_tty
    init

    #db_msg "$start_str"
    main_loop
}

init() {
    re_init
    select_menu main_cc
}

re_init() {
    screen_init
    new_menu     main_cc $"Main Menu"                make_main_menu
    new_menu     live_cc $"antiX Live Commands"      make_live_menu
    new_menu       av_cc $"Audio/Visual Commands"    make_av_menu
    new_menu sys_tool_cc $"System Tools"             make_sys_tool_menu
    new_menu sys_info_cc $"System Information"       make_sys_info_menu
    new_menu  console_cc $"Console Utilities"        make_console_menu
    new_menu      net_cc $"Internet Applications"    make_net_menu
    new_menu      off_cc $"Office Applications"      make_off_menu
    new_menu   config_cc $"Configuration Files"      make_config_menu

    if its_alive; then
        new_menu   logout_cc $"Logout / Installer"     make_logout_menu
    else
        new_menu   logout_cc $"Logout / Reboot"        make_logout_menu
    fi

}

key_callback() {
    local key=$1
    case $key in

        [mM]) db_msg "Main selection: $MAIN_CC_SEL"     ;;
        [bB]) under_main_cc && select_menu $PARENT_MENU ;;

    q|escape) in_main_cc && clear && exit
              select_menu $PARENT_MENU $MAIN_CC_SEL     ;;

           *) return 1;;
    esac
    return 0
}

make_main_menu() {
    start_menu_list
    entry $"Audio/Visual menu"
    entry $"Internet Tools & Apps"
    entry $"System Tools"
    entry $"System Information"
    entry $"Configuration Files"
    entry $"Live System Centre"

    in_vt && entry $"Console Utilities"

    entry $"Office and Other"
    if its_alive; then
        entry $"Logout / Install"
    else
        entry $"Logout / Reboot"
    fi
    entry "$(printf "$yellow%s" $"Quit")"
}

main_cc_on_enter() {
    local name=$1 sel=$3

    MAIN_CC_SEL=$sel

    case $name in
           $"Audio/Visual menu") select_menu av_cc           ;;
       $"Internet Tools & Apps") select_menu net_cc          ;;
                $"System Tools") select_menu sys_tool_cc     ;;
          $"System Information") select_menu sys_info_cc     ;;
         $"Configuration Files") select_menu config_cc       ;;
          $"Live System Centre") select_menu live_cc         ;;
           $"Console Utilities") select_menu console_cc      ;;
            $"Office and Other") select_menu off_cc          ;;
            $"Logout / Install") select_menu logout_cc       ;;
             $"Logout / Reboot") select_menu logout_cc       ;;
                        $"Quit") clear ; exit 0              ;;

      *) db_msg $"Would do action %s" "$white$name" ; return ;;
    esac
}


make_logout_menu() {
    start_menu_list

    its_alive && add_cmd 'cli-installer' $"Install this distro on a hard drive"
    add_cmd 'reboot'            $"Reboot the system"
    add_cmd 'poweroff'          $"Powerdown the system"

    end_menu_list
    back_to_main_entry
}

logout_cc_cmd() {
    local name=$1 sel=$3

    case $name in
            cli-installer) run_cmd -spc  $cmd      ;;
                   reboot) run_cmd -sc telinit 6   ;;
                 poweroff) run_cmd -sc telinit 0   ;;

        *) db_msg "Would do logout action %s" "$white$name" ; return ;;
    esac
}

make_av_menu() {
    start_menu_list

    local wallpaper=$(wallpaper)

    add_cmd speaker-test             $"See if sound is working"
    add_cmd alsa-set-default-card    $"Select which sound card to use"
    add_cmd alsamixer                $"simple sound mixer"
    add_cmd mocp                     $"Audio Player"
    add_cmd "mocp --exit"            $"Stop mocp Audio Player"
    add_cmd mpv                      $"Video Player"
    add_cmd mpsyt                    $"YouTube audio-only jukebox"
    add_cmd pmrp                     $"Poor Man's Radio Player"
    # add_cmd burniso                  "cd/dvd burner"
    in_vt && [ ${#wallpaper} -gt 0 ] \
        && add_cmd fbi               $"Image viewer"
    in_vt && add_cmd fbgs            $"Pdf viewer"
    add_cmd cdw                      $"cd/dvd burner"

    end_menu_list
    back_to_main_entry
}

av_cc_cmd() {
    local cmd=$1
    local mpv_drv
    in_vt && mpv_drv=--vo=drm
    case $cmd in
                 speaker-test) run_cmd     $cmd -c 2 -t wav -l 2 ;;
        alsa-set-default-card) run_cmd  -p $cmd --cli            ;;
                    alsamixer) run_cmd     $cmd                  ;;
                         mocp) run_cmd     $cmd $PLAY_LIST       ;;
                "mocp --exit") run_cmd     $cmd                  ;;
                          mpv) run_cmd     $cmd $mpv_drv --ytdl "$YT_DEMO" ;;
                         pmrp) run_cmd     $cmd                  ;;
                        mpsyt) run_cmd     $cmd //antiX Linux    ;;
                          fbi) run_cmd     $cmd -a $(wallpaper)  ;;
                         fbgs) run_cmd     $cmd $(pdf_file)      ;;
                      burniso) run_cmd     $cmd                  ;;
                          cdw) run_cmd     $cmd                  ;;

        *)  db_msg "Would do action %s" "$white$cmd"
    esac
    return
}

# we could search more if ever needed
wallpaper() { ls $WALLPAPER_DIR/*.jpg 2>/dev/null ; }
pdf_file()  { ls /usr/share/cups/data/default-testpage.pdf 2>/dev/null ; }

make_sys_tool_menu() {
    start_menu_list
    add_cmd cli-aptiX             $"Install new packages (like Synaptic)"
    #add_cmd smxi                  $"System maintenance tool"
    add_cmd ddm-mx                $"Install nvidia non-free graphics drivers (for X)"
    add_cmd testdisk              $"Check and undelete disk partitions"
    add_cmd sysv-rc-conf          $"Choose startup services"
    add_cmd tzdata                $"Set date and time"  dpkg-reconfigure
    #add_cmd guess-hwclock         $"Be prompted to set up the time correctly"
    #add_cmd htop                  $"Monitor and Control Processes"

    local dev

    for dev in /dev/sd?; do
        add_cmd "cfdisk $dev"   "$(printf $"Partition block device %s" "${dev##*/}")"
    done

    end_menu_list
    back_to_main_entry
}

sys_tool_cc_cmd() {
    local cmd=$1
    case $cmd in
                cli-aptiX)  run_cmd -s  $cmd                     ;;
                 testdisk)  run_cmd -s  $cmd                     ;;
             sysv-rc-conf)  run_cmd -s  $cmd                     ;;
                   tzdata)  run_cmd -s  dpkg-reconfigure  $cmd   ;;
            guess-hwclock)  run_cmd -s  $cmd                     ;;
                     htop)  run_cmd -s  $cmd                     ;;
                     smxi)  sudo su - -c "$cmd -G -! 32"         ;;
                   ddm-mx)  run_cmd -s  $cmd -i nvidia           ;;
                  cfdisk*)  run_cmd -s  $cmd                     ;;
        *)  db_msg "Would do action %s" "$white$cmd"
    esac
    return
}

make_sys_info_menu() {
    start_menu_list
    add_cmd htop                   $"Monitor and control processes"
    add_cmd inxi                   $"Hardware and OS information"
    add_cmd env-info               $"Other system information"
    add_cmd ps_mem.py              $"Show memory usage"
    add_cmd df                     $"Information about mounted partitions"
    add_cmd lsblk                  $"List all block (disk) partitions"
    add_cmd lsmod                  $"List currently installed kernel modules"
    add_cmd lspci                  $"List major system components"
    add_cmd lsusb                  $"List attached USB devices"
    add_cmd dmesg                  $"Display messages from the kernel"
    add_cmd pinfo                  $"View information about various commands"
    add_cmd parted                 $"View and edit disk partitions"
    add_view $"X Server Log File"    /var/log/Xorg.0.log
    add_view $"Live Boot Log File"   /var/log/live/initrd.log.color

    end_menu_list
    back_to_main_entry
}


sys_info_cc_cmd() {
    local cmd=$1
    case $cmd in
             htop)  run_cmd     $cmd                     ;;
             inxi) view_cmd     $cmd -Fx -c24            ;;
         env-info) view_cmd     $cmd                     ;;
        ps_mem.py) view_cmd -s  $cmd                     ;;
               df) view_cmd     $cmd -hTP                ;;
            pinfo) view_cmd     $cmd                     ;;
            lsblk) view_cmd -s  $cmd -o NAME,SIZE,FSTYPE,LABEL,MOUNTPOINT ;;
            lsmod) view_cmd     $cmd                     ;;
            lspci) view_cmd     $cmd                     ;;
            lsusb) view_cmd     $cmd                     ;;
            dmesg) view_cmd     $cmd --color=always --ctime  ;;
           parted) view_cmd -s  $cmd --list              ;;

            Xorg.0.log) view_file /var/log/Xorg.0.log ;;
      initrd.log.color) view_file /var/log/live/initrd.log.color ;;

        *)  db_msg "Would do action %s" "$white$cmd"
    esac
    return
}

make_live_menu() {
    start_menu_list
    add_cmd live-usb-maker       $"Make a full featured antiX or MX live-usb"
    add_cmd dd-live-usb          $"Make a "dd" live-usb for other distros"
    add_cmd live-kernel-updater  $"Update live kernel"
    add_cmd live-remaster        $"Remaster live system"
    add_cmd persist_save         $"Save dynamic root persistence"
    add_cmd persist-makefs       $"Configure dynamic root persistence"
    add_cmd persist-config       $"Create live persistence files"
    end_menu_list
    back_to_main_entry
}

live_cc_cmd() {
    local cmd=$1
    case $cmd in
             live-usb-maker) run_cmd -sp $cmd         ;;
                dd-live-usb) run_cmd -sp $cmd         ;;
        live-kernel-updater) run_cmd -sp $cmd         ;;
              live-remaster) run_cmd -sp $cmd --cli   ;;
               persist_save) run_cmd -sp $cmd --cli   ;;
             persist-makefs) run_cmd -sp $cmd --cli   ;;
             persist-config) run_cmd -sp $cmd --cli   ;;
                          *)  db_msg "Would do action %s" "$white$cmd"
    esac
}

make_console_menu() {
    start_menu_list

    have_backlight \
        && add_cmd backlight-brightness  $"Adjust the brightness of the backlight"

    add_cmd splash-select         $"Choose the console background"
    add_cmd console-width-select  $"Choose the console font"
    add_cmd console-font-select   $"Choose the console font"
    add_cmd ansi-colors           $"Display all possible console text colors"
    #add_cmd space-evaders         $"Arcade type game"
    [ $UID -eq 0 ] \
        && add_cmd tao            $"Excerpts from the Tao of Programming"

    add_cmd vlock                 $"Lock the virtual consoles"
    end_menu_list
    back_to_main_entry
}

console_cc_cmd() {
    local cmd=$1
    case $cmd in
       backlight-brightness) run_cmd     $cmd    ;;
              splash-select) run_cmd     $cmd    ;;
        console-font-select) run_cmd     $cmd    ;;
       console-width-select) run_cmd -s  $cmd    ;;
       choose-console-width) run_cmd -s  $cmd    ;;
                ansi-colors) view_cmd    $cmd    ;;
              space-evaders) run_cmd     $cmd    ;;
                        tao) run_cmd -p  $cmd    ;;
                      vlock) run_cmd     $cmd -a ;;

        *)  db_msg "Would do action %s" "$white$cmd"
    esac
}

make_net_menu() {
    start_menu_list

    pgrep -x connmand &>/dev/null \
        || add_cmd ceni      $"Set up wired/wireless"
    add_cmd connmanctl       $"Set up wired/wireless"
    add_cmd ifconfig         $"Show network status"
    add_cmd ping             $"Test if network is connected"
    add_cmd speedtest-cli    $"Test network bandwidth"
    add_cmd netstat          $"Show all network connections and ports"
    add_cmd netpro           $"Manage network profiles"
    add_cmd curl             $"Weather forecast"
    add_cmd mutt             $"Email client"
    add_cmd alpine           $"Email client"
    add_cmd elinks           $"Web browser (text mode)"
    #add_cmd links2           $"Web browser (text mode)"
    in_vt && add_cmd 'links2 -g'     $"Web browser (graphics mode)"

    add_cmd irrsi            $"Chat client"
    add_cmd newsbeuter       $"RSS/Atom feed reader"
    add_cmd rtorrent         $"BitTorrent client"

    end_menu_list
    back_to_main_entry
}

net_cc_cmd() {
    local cmd=$1
    case $cmd in
               ping) run_cmd -p  $cmd -c3 -W1 8.8.8.8 ;;
           ifconfig) run_cmd -p  $cmd                 ;;
            netstat) run_cmd -ps $cmd -autp           ;;
      speedtest-cli) run_cmd -p  $cmd                 ;;
               ceni) run_cmd -s  $cmd                 ;;
         connmanctl) run_cmd -s  $cmd                 ;;
        wicd-curses) run_cmd -s  $cmd                 ;;
             netpro) run_cmd -s  $cmd                 ;;
             elinks) run_cmd -g  $cmd $BOOKMARKS      ;;
             links2) run_cmd     $cmd $BOOKMARKS      ;;
        "links2 -g") run_cmd -sg $cmd $BOOKMARKS      ;;

               curl) $cmd wttr.in | less -SR
                     echo "$cmd wttr.in" >> $cmd_file ;;

               mutt) run_cmd     $cmd                 ;;
             alpine) run_cmd     $cmd                 ;;
              irrsi) run_cmd     $cmd                 ;;
         newsbeuter) run_cmd     $cmd                 ;;
           rtorrent) run_cmd     $cmd                 ;;

        *)  db_msg "Would do action %s" "$white$cmd"
    esac
}

make_off_menu() {
    start_menu_list

    add_cmd mc            $"Midnight commander file manager"
    add_cmd wordgrinder   $"Word Processor"
    add_cmd calcurse      $"Calendar/Schedule"
    add_cmd nano          $"Simple text editor"
    add_cmd sc            $"Spreadsheet calculator"
    add_cmd vim           $"Advanced text editor"

    end_menu_list
    back_to_main_entry
}

off_cc_cmd() {
    local cmd=$1
    case $cmd in
                     mc) run_cmd  $cmd    ;;
            wordgrinder) run_cmd  $cmd    ;;
               calcurse) run_cmd  $cmd    ;;
                   nano) run_cmd  $cmd    ;;
                    vim) run_cmd  $cmd    ;;
                      sc) run_cmd  $cmd    ;;
               *)  db_msg "Would do action %s" "$white$cmd"
    esac
}

make_config_menu() {
    start_menu_list
    add_edit $"File system table"               /etc/fstab
    add_edit $"X Windows Configuration"         /etc/X11/xorg.conf
    add_edit $"SLiM Graphical login manager"    /etc/slim.conf
    add_edit $"Installed bootloader"            /boot/grub.menu.lst

    its_alive_usb && add_edit $"Live usb BIOS bootloader"  /live/boot-dev/boot/syslinux/syslinux.cfg
    its_alive_usb && add_edit $"Live usb UEFI bootloader"  /live/boot-dev/boot/grub/grub.cfg

    add_edit $"Remaster Exclude List"           /usr/local/share/excludes/general-remaster-exclude.list
    add_edit $"Snapshot Exclude List"           /usr/local/share/excludes/iso-snapshot-exclude.list
    add_edit $"Remaster Exclude List 2"         /usr/local/share/excludes/live-remaster-exclude.list
    add_edit $"Persist Save Exclude List"       /usr/local/share/excludes/persist-save-exclude.list

    end_menu_list
    back_to_main_entry
}

config_cc_cmd() {
    local cmd=$1
    case $cmd in

        general-remaster-exclude.list) edit_file -s /usr/local/share/excludes/general-remaster-exclude.list  ;;
            iso-snapshot-exclude.list) edit_file -s /usr/local/share/excludes/iso-snapshot-exclude.list      ;;
           live-remaster-exclude.list) edit_file -s /usr/local/share/excludes/live-remaster-exclude.list     ;;
            persist-save-exclude.list) edit_file -s /usr/local/share/excludes/persist-save-exclude.list      ;;

               fstab) edit_file -s /etc/fstab          ;;
           xorg.conf) edit_file -s /etc/X11/xorg.conf  ;;
           slim.conf) edit_file -s /etc/slim.conf      ;;
           menu.list) edit_file -s /boot/grub/menu.lst ;;
        syslinux.cfg) edit_file -s /live/boot-dev/boot/syslinux/syslinux.cfg ;;
            grub.cfg) edit_file -s /live/boot-dev/boot/grub/grub.cfg ;;

               *)  db_msg "Would do action %s" "$white$cmd"
    esac
}

yt_demo() {
    local demo  i=$(($RANDOM % YT_DEMO_NUM))
    eval demo=\$YT_DEMO_$i
    echo $demo
}

have_backlight() {
    local f
    for f in /sys/class/backlight/*/brightness; do
        test -e $f && return 0
    done
    return 1
}

HELP_PAGE=$ME

[ "$DEBUG" ] || log_file=/dev/null

cmd_file=$HOME/$ME.cmd

test -e $cmd_file && echo >>$cmd_file
echo -e "$ME started $(date)" >>$cmd_file

main "$@" 2>> $log_file
