#!/bin/bash

##########################################################
# Copyright (c) 2001-2024 Alexey Kuryakin daqgroup@mail.ru
##########################################################
# CrwKit script to run useful DaqGroup`s "cherry" scripts.
##########################################################

################################
# Current script identification.
################################
readonly startupdir="$(pwd -LP)";
readonly scriptfile="${BASH_SOURCE[0]}";
readonly scriptname="$(basename $scriptfile)";
readonly scriptbase="$(basename $scriptfile .sh)";
readonly scripthome="$(dirname  $scriptfile)";
readonly scriptFILE="$(realpath $scriptfile)";
readonly scriptHOME="$(dirname  $scriptFILE)";

readonly column_width=80;
readonly cherry_dirs="$scriptHOME /mnt/data/root/scripts";

#############################################################################################################################
# https://stackoverflow.com/questions/1763891/is-it-possible-to-make-stdout-and-stderr-output-be-of-different-colors-in-xterm
#############################################################################################################################
function colorize_norm()( set -o pipefail; ( "$@" 2>&1>&3 | sed $'s,.*,\e[31m&\e[m,'   >&2 ) 3>&1 | sed $'s,.*,\e[32m&\e[m,'   );
function colorize_bold()( set -o pipefail; ( "$@" 2>&1>&3 | sed $'s,.*,\e[1;31m&\e[m,' >&2 ) 3>&1 | sed $'s,.*,\e[1;32m&\e[m,' );
function colorize_head()( set -o pipefail; ( "$@" 2>&1>&3 | sed $'s,.*,\e[1;35m&\e[m,' >&2 ) 3>&1 | sed $'s,.*,\e[1;37m&\e[m,' );
function colorize_none()( "$@"; );

##################################
# Uses language dependent strings?
##################################
declare -i uses_langstr=1;

################################
# Language dependent string echo
# langstr en 'Hello' ru 'Привет'
################################
function langstr(){
 local lng="en"; local msg="";
 if [ "$uses_langstr" = "1" ]; then lng="${LANG:0:2}"; fi;
 while [ -n "$lng" ] && [ -n "$1" ] && [ -n "$2" ]; do
  if [ "$lng" = "$1" ]; then msg="$2"; break; fi;
  if [ "$lng" = "en" ]; then msg="$2"; fi;
  if [ "$lng" = "us" ]; then msg="$2"; fi;
  if [ "$lng" = "uk" ]; then msg="$2"; fi;
  shift; shift;
 done;
 if [ -n "$msg" ]; then echo "$msg"; fi;
};

function do_version(){
 echo "$scriptname version 1.0";
};

function do_help(){
 colorize_head echo "########################################################";
 colorize_none echo "Copyright (c) 2001-2024 Alexey Kuryakin daqgroup@mail.ru";
 colorize_bold echo "CrwKit script to run useful DaqGroup\`s \"cherry\" scripts.";
 colorize_head echo "Usage:";
 colorize_bold echo " crwkit cherry [-options] [arguments]";
 colorize_head echo "Options:";
 colorize_norm echo " -h,--help      - show help";
 colorize_norm echo " --version      - show version";
 colorize_head echo "Arguments:";
 colorize_bold echo " command [parameters]";
 colorize_norm echo " where command is one of listed:";
 colorize_none print_cherry_table;
 colorize_head echo "Examples:";
 colorize_norm echo " crwkit cherry firefox-backup";
 colorize_head echo "########################################################";
};

################################
# print $1 to stderr without EOL
################################
function print_stderr(){
 1>&2 echo -ne "$1";
};

##############################
# fatal error message and exit
##############################
function fatal(){
 if [ -t 1 ] && [ -t 2 ]; then
  colorize_bold print_stderr "\n\n$2\n\n";
 else
  print_stderr "\n\n$2\n\n";
 fi;
 exit $1;
};

##########################
# unsorted raw cherry list
##########################
function raw_cherry_list(){
 for dir in $*; do
  if [ -d $dir ]; then
   find $dir -type f -executable   -name '*.sh' | xargs -n 1 -I {} basename {} .sh;
   find $dir -type f -executable ! -name '*.*'  | xargs -n 1 -I {} basename {} .sh;
  fi;
 done;
};

###################################
# print sorted cherry list as table
###################################
function print_cherry_table(){
 raw_cherry_list $cherry_dirs | sort | uniq | column -s ' ' -c $column_width;
};

########################
# cherry: command to run
# find cherry by name $1
# in directories list $2
########################
function find_cherry(){
 if [ $# -eq 2 ]; then
  local berry="$(basename "$1" .sh)";
  for dir in $2; do
   local cherry="$(realpath "$dir/$berry")";    if [ -f "$cherry" ] && [ -x "$cherry" ]; then echo -n "$cherry"; break; fi;
   local cherry="$(realpath "$dir/$berry.sh")"; if [ -f "$cherry" ] && [ -x "$cherry" ]; then echo -n "$cherry"; break; fi;
  done;
 fi;
};

function cherry_note(){
 case $1 in
  '') ;;
  show-ls-colors)           langstr ru "Показать цветовую палитру команды ls." \
                                    en "Show color palette of command ls."; ;;
  firefox-backup)           langstr ru "Сохранение копии настроек FireFox." \
                                    en "Save FireFox settiongs backup copy."; ;;
  astra-download-mirror)    langstr ru "Загрузка зеркала репозитория AstraLinux из Интернета на HDD." \
                                    en "Download mirror of AstraLinux repository from Internet to HDD."; ;;
  astra-http-mirror)        langstr ru "Запуск локального HTTP репозитория AstraLinux." \
                                    en "Launch local HTTP mirror of AstraLinux repository."; ;;
  astra-rsync-hdd-to-ufd)   langstr ru "HDD->UFD: Копия зеркала AstraLinux с Диска (HDD) на Флешку (UFD)." \
                                    en "HDD->UFD: Copy AstraLinux repository mirror from HardDisk (HDD) to USB/Flash (UFD)."; ;;
  astra-rsync-net-to-hdd)   langstr ru "NET->HDD: Копировать зеркало AstraLinux из Локальной Сети (NET) на Диск (HDD)." \
                                    en "NET->HDD: Copy AstraLinux repository mirror from Network (NET) to HardDisk (HDD)."; ;;
  astra-rsync-ufd-to-hdd)   langstr ru "UFD->HDD: Копия зеркала AstraLinux с Флешки (UFD) на Диск (HDD)." \
                                    en "UFD->HDD: Copy AstraLinux repository mirror from USB/Flash (UFD) to HardDisk (HDD)"; ;;
  astra-setup)              langstr ru "Начальные установки пакетов AstraLinux для DaqGroup." \
                                    en "AstraLinux initial package setup required for DaqGroup."; ;;
  astra-sources)            langstr ru "Выбор источника ПО (расположения репозитория) AstraLinux." \
                                    en "Choose AstraLinux repository location."; ;;
  astra-tweak)              langstr ru "Настроить каталоги и параметры AstraLinux для DaqGroup." \
                                    en "Tweak AstraLinux user directories and parameters for DaqGroup."; ;;
  astra-update)             langstr ru "Проверить и обновить пакеты AstraLinux." \
                                    en "Update and upgrage packages of AstraLinux."; ;;
  make-mime-types-markdown) langstr ru "Записать ~/.mime.types файл для Firefox для просмотра Markdown и других файлов." \
                                    en "Make ~/.mime.types file for Firefox to view Markdown and other file types."; ;;
  ssh-mount-crw-daq-su)     langstr ru "Примонтировать crw-daq.su через SSH." \
                                    en "Mount crw-daq.su via SSH."; ;;
  ssh-umount-crw-daq-su)    langstr ru "Отмонтировать crw-daq.su через SSH." \
                                    en "Unmount crw-daq.su via SSH."; ;;
  *)                        langstr ru "Утилита $1" \
                                    en "Utility $1"; ;;
 esac;
};

function do_zen(){
 local args=();
 local title="$(langstr ru "Запуск утилиты из набора DaqGroup Cherry:" en "Run Utility from toolset DaqGroup Cherry:")";
 local text="$(langstr ru "Выбирите утилиту для запуска:" en "Choose utility to run:")";
 args+=( --title "$title" --text "$text"                     );
 args+=( --width 1024 --height 600                           );
 args+=( --list --print-column 1                             );
 args+=( --column "$(langstr ru "Команда" en "Command")"     );
 args+=( --column "$(langstr ru "Комментарий" en "Comment")" );
 for item in $(print_cherry_table | xargs); do
  if [ "$item" = "$scriptbase" ]; then continue; fi;
  args+=( "$item" "$(cherry_note "$item")" );
 done;
 local item="$(zenity "${args[@]}" 2>/dev/null)";
 if [ -n "$item" ]; then
  handle_params "$item";
 fi;
};

################################
# handle command line parameters
################################
function handle_params(){
 if [ -n "$1" ]; then
  local cmd="$(find_cherry "$1" "$cherry_dirs")";
  if [ -n "$cmd" ]; then
   shift; # skip command to get arguments
   echo    exec unix grun xterm -hold -e $cmd "$@";
           exec unix grun xterm -hold -e $cmd "$@";
  else
   fatal 1 "Error: unknown command $1.";
  fi;
 fi;
};

######################
# main function to run
######################
function main(){
 if [ -n "$1" ]; then
  case $1 in
   -h|-help|--help)    do_help; ;;
   -version|--version) do_version; ;;
   -zen|--zen)         do_zen; ;;
   -*)                 fatal 1 "Error: invalid option $1."; ;;
   *)                  handle_params "$@"; ;;
  esac;
 else
  fatal 1 "Error: missed arguments. Call $scriptname -h to get help.";
 fi;
};

main "$@";

#############
# END OF FILE
#############
