#!/bin/sh

function about(){
 echo "#########################################################";
 echo "# Copyright (c) 2023 Alexey Kuryakin kouriakine@mail.ru #";
 echo "# Control Panel for Diesel Pascal interpreter language. #";
 echo "#########################################################";
};

readonly icon_run="/usr/share/pixmaps/CrossMachine.png";
readonly icon_ide="/usr/share/pixmaps/CrossDesigner.png";
readonly initscript="/opt/diesel/examples/tetris.lm9";
readonly envoptconf="$HOME/.DieselPascal/EnvOptions.xml";
readonly syncolconf="$HOME/.DieselPascal/SynColors.cfg";
readonly runhistory="$HOME/.DieselPascal/run.history";
readonly idehistory="$HOME/.DieselPascal/ide.history";
readonly txthistory="$HOME/.DieselPascal/history.txt";
readonly envarsconf="$HOME/.DieselPascal/evars.cfg";
readonly maxhistory="1024";

function launch(){
 echo launch: "$@";
 "$@" >/dev/null 2>&1 & disown;
};

function makeuniq(){
 if [ -n "$1" ] && [ -e "$1" ]; then
  cp $1 $1.tmp;
  cat $1.tmp | uniq | tail -n $maxhistory > $1;
  rm -f $1.tmp;
 fi;
};

function saveuniq(){
 if [ -n "$1" ] && [ -n "$2" ]; then
  echo "$2" >> $1;
  makeuniq $1;
 fi;
};

function backup_file(){
 if [ -n "$1" ] && [ -e "$1" ]; then
  local dir="$(dirname $1)";
  local name="$(basename $1)";
  [ -e $dir/backup ] || mkdir $dir/backup;
  cp -f $1 $dir/backup/$name && { echo "backup: $1 => $dir/backup/$name"; };
 fi;
};

function cleanup_backup_file(){
 if [ -n "$1" ] && [ -e "$1" ]; then
  local dir="$(dirname $1)";
  local name="$(basename $1)";
  [ -e $dir/backup ] || mkdir $dir/backup;
  mv -f $1 $dir/backup/$name && { echo "cleanup: $1 => $dir/backup/$name"; };
 fi;
};

function is_number(){
 case $1 in
  ''|*[!0-9]*)  return 1; ;;
  *)            return 0; ;;
 esac;
};

let uses_langstr=1;

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 diesel_open(){
 local filename="$initscript";
 if [ -e $idehistory ]; then
  local last="$(cat $idehistory | tail -n 1)";
  [ -n "$last" ] && [ -e "$last" ] && filename="$last";
 fi;
 echo "last open: $filename";
 local title="$(langstr en 'Open Diesel Pascal Project …' ru 'Открыть Проект Diesel Pascal …')";
 local script="$(\
        zenity --title "$title"         \
        --window-icon $icon_ide         \
        --file-selection --modal        \
        --filename $filename            \
        --file-filter 'LM9|*.[Ll][Mm]9' \
        --file-filter 'ALL|*.*'         \
        2>/dev/null)";
 if [ -n "$script" ] && [ -e "$script" ]; then
  echo "this open: $script";
  saveuniq $idehistory $script;
  launch /opt/diesel/CrossDesigner $script;
 fi;
};

function diesel_run(){
 local filename="$initscript";
 if [ -e $runhistory ]; then
  local last="$(cat $runhistory | tail -n 1)";
  if [ -n "$last" ] && [ -e "$last" ]; then filename="$last"; fi;
 fi;
 echo "last run: $filename";
 local title="$(langstr en 'Run Diesel Pascal Project …' ru 'Запустить Проект Diesel Pascal …')";
 local script="$(\
        zenity --title "$title"         \
        --window-icon $icon_run         \
        --file-selection --modal        \
        --filename $filename            \
        --file-filter 'LM9|*.[Ll][Mm]9' \
        --file-filter 'ALL|*.*'         \
        2>/dev/null)";
 if [ -n "$script" ] && [ -e "$script" ]; then
  echo "this run: $script";
  saveuniq $runhistory $script;
  launch /opt/diesel/CrossMachine $script;
 fi;
};

function diesel_open_past(){
 local num="10"; if is_number $1; then num="$1"; fi;
 local filename="$initscript";
 if [ -e $idehistory ]; then
  local list="$(tac $idehistory | uniq | awk '!seen[$0]++' | head -n $num)";
  if [ -n "$list" ]; then local temp=" "; for item in $list; do if [ -e "$item" ]; then temp="$temp $item"; fi; done; list="$(echo $temp)"; fi;
  if [ -n "$list" ]; then
   local titl="$(langstr en 'Select past Diesel Pascal Project …' ru 'Выбор прошлого проекта Diesel Pascal …')";
   local text="$(langstr en 'Please select <b>Diesel Pascal</b> project opened past …' ru 'Выбирете недавно открытый проект <b>Diesel Pascal</b> …')";
   local clmn="$(langstr en 'Project file name:' ru 'Имя файла проекта:')";
   local last="$(\
        zenity --title "$titl" --text "$text"                   \
        --timeout 180 --width 600 --height 400 --separator ' '  \
        --list --column "$clmn" $list                           \
        2>/dev/null)";
   if [ -z "$last" ]; then return 0; fi;
   if [ -n "$last" ] && [ -e "$last" ]; then filename="$last"; fi;
  fi;
 fi;
 echo "last open: $filename";
 local title="$(langstr en 'Open Diesel Pascal Project …' ru 'Открыть Проект Diesel Pascal …')";
 local script="$(\
        zenity --title "$title"         \
        --window-icon $icon_ide         \
        --file-selection --modal        \
        --filename $filename            \
        --file-filter 'LM9|*.[Ll][Mm]9' \
        --file-filter 'ALL|*.*'         \
        2>/dev/null)";
 if [ -n "$script" ] && [ -e "$script" ]; then
  echo "this open: $script";
  saveuniq $idehistory $script;
  launch /opt/diesel/CrossDesigner $script;
 fi;
};

function diesel_run_past(){
 local num="10"; if is_number $1; then num="$1"; fi;
 local filename="$initscript";
 if [ -e $runhistory ]; then
  local list="$(tac $runhistory | uniq | awk '!seen[$0]++' | head -n $num)";
  if [ -n "$list" ]; then local temp=" "; for item in $list; do if [ -e "$item" ]; then temp="$temp $item"; fi; done; list="$(echo $temp)"; fi;
  if [ -n "$list" ]; then
   local titl="$(langstr en 'Select past Diesel Pascal Project …' ru 'Выбор прошлого проекта Diesel Pascal …')";
   local text="$(langstr en 'Please select <b>Diesel Pascal</b> project run past …' ru 'Выбирете недавно запущеный проект <b>Diesel Pascal</b> …')";
   local clmn="$(langstr en 'Project file name:' ru 'Имя файла проекта:')";
   local last="$(\
        zenity --title "$titl" --text "$text"                   \
        --timeout 180 --width 600 --height 400 --separator ' '  \
        --list --column "$clmn" $list                           \
        2>/dev/null)";
   if [ -z "$last" ]; then return 0; fi;
   if [ -n "$last" ] && [ -e "$last" ]; then filename="$last"; fi;
  fi;
 fi;
 echo "last run: $filename";
 local title="$(langstr en 'Run Diesel Pascal Project …' ru 'Запустить Проект Diesel Pascal …')";
 local script="$(\
        zenity --title "$title"         \
        --window-icon $icon_run         \
        --file-selection --modal        \
        --filename $filename            \
        --file-filter 'LM9|*.[Ll][Mm]9' \
        --file-filter 'ALL|*.*'         \
        2>/dev/null)";
 if [ -n "$script" ] && [ -e "$script" ]; then
  echo "this run: $script";
  saveuniq $runhistory $script;
  launch /opt/diesel/CrossMachine $script;
 fi;
};

function diesel_defaults(){
 backup_file $envoptconf;
 backup_file $syncolconf;
 backup_file $envarsconf;
 /opt/diesel/settings/diesel-defaults.sh;
};

function diesel_cleanup(){
 cleanup_backup_file $runhistory;
 cleanup_backup_file $idehistory;
 cleanup_backup_file $txthistory;
};

function diesel_cpl_exec(){
 case "$1" in
  Open|open)
   diesel_open;
   ;;
  Open_past|open_past)
   diesel_open_past 100;
   ;;
  IDE|ide|New|new|CrossDesigner)
   launch /opt/diesel/CrossDesigner;
   ;;
  Run|run|CrossMachine)
   diesel_run;
   ;;
  Run_past|run_past|CrossMachine_past)
   diesel_run_past 100;
   ;;
  Manager|manager|DManager)
   launch /opt/diesel/DManager;
   ;;
  Defaults|defaults|diesel-defaults.sh)
   diesel_defaults;
   ;;
  Cleanup|cleanup)
   diesel_cleanup;
   ;;
  *)
   echo "${0##*/} {Open|IDE|New|CrossDesigner|Run|CrossMachine|Manager|DManager|Cleanup|Defaults|diesel-defaults.sh}";
   ;;
 esac;
};

function diesel_cpl_menu(){
 local titl="$(langstr en 'Diesel Pascal Control Panel …' ru 'Панель Управления Diesel Pascal …')";
 local text="$(langstr en 'Select wanted <b>Action</b>:' ru 'Выбирайте желаемое <b>Действие</b>:')";
 local menu="$(\
    zenity --title "$titl" --width 630 --height 280                                     \
    --text "<b>Diesel Pascal</b> - $text" --timeout 180 --modal --window-icon $icon_ide \
    --list --column 'ID' --column 'Действие' --column 'Action' --print-column 1         \
    Run         'Запуск проекта (последний) '   'Run  Diesel Pascal Project (last)  '   \
    Open        'Открыть проект (последний) '   'Open Diesel Pascal Project (last)  '   \
    Run_past    'Запуск проекта (из списка) '   'Run  Diesel Pascal Project (past)  '   \
    Open_past   'Открыть проект (из списка) '   'Open Diesel Pascal Project (past)  '   \
    IDE         'Открыть Дизайнер проектов  '   'Diesel Pascal Designer IDE         '   \
    Manager     'Открыть Менеджер проектов  '   'Diesel Pascal Project Manager      '   \
    Cleanup     'Очистка Истории проектов   '   'Clear history of run projects      '   \
    Defaults    'Сброс настроек Дизайнера   '   'Reset IDE Setting to Defaults      '   \
    2>/dev/null)";
 if [ -n "$menu" ]; then diesel_cpl_exec "$menu"; fi;
};

function main(){
 about; sleep 1;
 diesel_cpl_menu "$@";
};

main "$@";

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