#!/bin/bash

###########################################################
## Copyright (c) 2002-2025 Alexey Kuryakin daqgroup@mail.ru
###########################################################

###########################################################
## Utility to control Firebird/Interbase server/client.
###########################################################

###########################################################
source $(crwkit which crwlib_base.sh); # Use base library #
source $(crwkit which crwlib_file.sh); # Use file library #
###########################################################

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

function show_help(){
 show_vers;
 echo "Copyright (c) 2001-2025 Alexey Kuryakin daqgroup@mail.ru";
 echo "Firebird/Interbase server/client control panel tool.";
 echo "Usage: ${scriptname} [-options]";
 echo "Options:";
 echo " -h,--help         - show help";
 echo " --version         - show version";
 echo " -l,--list         - list firebird server's pid cmd";
 echo " -w,--which        - print firebird binary pathname";
 echo " -s,--status       - see status of firebird service";
 echo " -r,--restart      - restart       firebird service";
 echo " -b,--start        - begin (start) firebird service";
 echo " -q,--stop         - quite (stop)  firebird service";
 echo " -c,--client       - print client library locations";
 echo " -u,--user         - add current user to group firebird";
 echo " -i,--install      - install firebird required packages";
 echo " -m,--menu         - show Menu - Firebird Control Panel";
 echo " -d,--desktop-menu - setup Desktop Menu in Start Button";
 echo " --desktop-drop    - drop  Desktop Menu in Start Button";
 echo " --run-flamerobin  - run FlameRobin administration tool";
 echo " --run-sqlectron   - run Sqlectron SQL Database Browser";
 echo " --run-antares     - run Antares - SQL Database Browser";
 echo " --run-sqlook      - run SQLook - Database Browser";
 echo " --dbdrivers       - prepare database drivers .jar";
 echo " --dbsamples       - prepare database samples";
 echo "Examples:";
 echo " $scriptname --help       # show help";
 echo " $scriptname --version    # show version";
 echo " $scriptname -l           # list firebird pid cmd";
 echo " $scriptname -s           # check firebird status";
 echo " $scriptname -i           # install firebird packages";
};

function firebird_list(){
 pgrep -af firebird;
};

function firebird_which(){
 unix whichis firebird;
};

function firebird_control(){
 unix sudoit /etc/init.d/firebird3.0 $1;
};

function firebird_client(){
 unix findlibso -f libfbclient.so;
};

function firebird_reconfig(){
 unix sudoit dpkg-reconfigure firebird3.0-server;
};

function firebird_install(){
 local aptlist="";
 local chklist="";
 chklist+=" firebird3.0-common";
 chklist+=" firebird3.0-server";
 chklist+=" firebird3.0-utils";
 chklist+=" firebird3.0-doc";
 chklist+=" firebird-dev";
 for item in $chklist; do
  if [[ -n $(dpkg -s $item 2>/dev/null | grep "Status: install ok installed") ]]; then
   echo "Already Installed: $item";
  else
   echo "Should be Install: $item";
   aptlist+=" $item";
  fi;
 done;
 if [[ -n "$aptlist" ]]; then
  unix sudoit aptitude install $aptlist;
 else
  echo "Nothing to install.";
 fi;
};

function firebird_user(){
 for user in $(groups); do
  if [[ "$user" = "firebird" ]]; then
   echo "User $(whoami) is already in group firebird.";
   return 0;
  fi;
 done;
 if unix sudoit usermod -a -G firebird $(whoami); then
  echo "User $(whoami) is now in group firebird.";
  echo "You need restart session to apply this.";
 else
  fatal 1 "Could not add user $(whoami) to group firebird.";
 fi;
};

function show_usage(){
 local optlist="--version|--help|--list|--which|--status|--start|--stop|--restart";
 optlist+="|--menu|--desktop-menu|--desktop-drop|--dbsamples|--dbdrivers";
 optlist+="|--run-flamerobin|--run-sqlectron|--run-antares";
 optlist+="|--run-sqlook";
 echo "Usage: $scriptname $optlist";
};

function execute(){
 colorize_head echo "$@";
                    "$@";
};

function firebird_menu(){
 local title="Firebird Control Panel …";
 local text="The script <b>$scriptname</b>";
 text+="\n uses to control the [<span fgcolor='blue'><b>Firebird</b></span>] server/client.";
 text+="\n\n <big><b>Please <span fgcolor='green'>choose the command</span>:</b></big>"
 sleep 1;
 while true; do
  item="$(zenity --title "$title" --text "$text"                        \
          --width 500 --height 660                                      \
          --list --print-column 1                                       \
          --column Command --column "Comment"                           \
          help             "Show Help                               |"  \
          ________________ "Firebird Install:_______________________|"  \
          install          "Install Firebird Server/Client packages |"  \
          user             "Add current User to group 'firebird'    |"  \
          reconfig         "Set SYSDBA password, default=masterkey  |"  \
          ________________ "Firebird Control:_______________________|"  \
          status           "firebird3.0.service - Status of service |"  \
          start            "firebird3.0.service - Start   service   |"  \
          stop             "firebird3.0.service - Stop    service   |"  \
          restart          "firebird3.0.service - Restart service   |"  \
          ________________ "Firebird Utilities: ____________________|"  \
          list             "Show list of running Firebirs Server(s) |"  \
          which            "Show location of Firebird Server binary |"  \
          client           "Show location of Client Libraries (.so) |"  \
          dbsamples        "Share DB samples (employee) for testing |"  \
          dbdrivers        "Share DB drivers (jdbc jar) for working |"  \
          run-flamerobin   "Run FlameRobin, Database Manager/Viewer |"  \
          run-sqlectron    "Run Sqlectron, Database SQL Client/View |"  \
          run-antares      "Run Antares, Database SQL Client/Viewer |"  \
          run-sqlook       "Run SQLook,  Database SQL Client/Viewer |"  \
          ________________ "________________________________________|"  \
          exit             "Exit this menu (same as Cancel)         |"  \
          ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ "¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|"  \
          2>/dev/null
         )";
  case $item in
   help|install|user|reconfig|status|start|stop|restart|list|which|client|dbsamples|dbdrivers|run-flamerobin|run-antares|run-sqlectron|run-sqlook)
    execute unix $scriptFILE --$item;
    echo " ";
    continue;
    ;;
   _*|¯*)
    continue;
    ;;
   ''|exit|*)
    return 0;
    ;;
  esac;
 done;
};

function sudo_true(){
 local cmd="sudo true";
 if unix sudoit true; then
  true;
 else
  if [[ -t 1 ]]; then
   $cmd;
  else
   exec xterm -fa 'PT Mono' -fs 12 -fg white -bg black -sb -rightbar -geometry 120x35+50+100 -title "$cmd" -e $cmd;
  fi;
 fi;
};

function firebird_menu_cpl(){
 sudo_true;
 local cmd="unix $scriptname --menu";
 if [[ -t 1 ]]; then
  firebird_menu;
 else
  exec xterm -fa 'PT Mono' -fs 12 -fg white -bg black -sb -rightbar -geometry 120x35+50+100 -title "$cmd" -e $cmd;
 fi;
};

function copy_dbdrivers(){
 local sourdir="$scriptHOME/../dbdrivers";
 local targdir="/opt/daqgroup/share/dbdrivers";
 if [[ ! -e $targdir ]]; then unix sudoit mkdir -v -m 755 $targdir; fi;
 if [[ -e $sourdir ]] && [[ -e $targdir ]]; then
  unix sudoit cp -ufvr $sourdir/* $targdir/;
  unix sudoit find $targdir -type d | xargs -L1 unix sudoit chmod -c 755;
  unix sudoit chmod -cR ugo+r $targdir/*;
 fi;
};

function copy_dbsamples(){
 local sourdir="$scriptHOME/../dbsamples";
 local targdir="/opt/daqgroup/share/dbsamples";
 if [[ ! -e $targdir ]]; then unix sudoit mkdir -v -m 777 $targdir; fi;
 if [[ -e $sourdir ]] && [[ -e $targdir ]]; then
  unix sudoit cp -ufv $sourdir/* $targdir/;
  unix sudoit chown -c firebird:firebird $targdir/*.fdb;
  unix sudoit chmod -c ugo+rw $targdir/*;
 fi;
};

function print_employee(){
 echo "";
 echo "#";
 echo "# Example Database:";
 echo "#";
 echo "employee.fdb = /opt/daqgroup/share/dbsamples/employee.fdb";
 echo "employee = /opt/daqgroup/share/dbsamples/employee.fdb";
 echo "";
};

function demo_dbsamples(){
 local conf="/etc/firebird/3.0/databases.conf";
 if [[ -e $conf ]] && [[ -z $(cat $conf | grep -P '^\s*employee\s*=') ]]; then
  unix sudoit cp -fpv $conf $conf.backup;
  print_employee | unix sudoit tee -a $conf;
 fi;
};

function fix_wirecrypt(){
 local conf="/etc/firebird/3.0/firebird.conf";
 if [[ -e $conf ]] && [[ -z $(cat $conf | grep -P '^\s*WireCrypt\s*=\s*Enabled') ]]; then
  local num="$(cat $conf | grep -n -P '^\s*#\s*WireCrypt\s*=' | head -n1 | cut -d: -f1)";
  if is_number $num; then
   unix sudoit cp -fpv $conf $conf.backup;
   let num++; note "Insert line after #WireCrypt = …";
   if unix sudoit sed -i "${num}iWireCrypt = Enabled" $conf; then
    unix $scriptFILE --restart;
   fi;
  fi;
 fi;
};

function make_dbsamples(){
 copy_dbsamples;
 demo_dbsamples;
 fix_wirecrypt; 
};

function copy_sqlook(){
 local sqlook="$(realpath $(unix which sqlook))";
 if [[ -n $sqlook ]] && [[ -x $sqlook ]]; then
  local sqlookdir="$(dirname $sqlook)";
  local png="$sqlookdir/sqlook.png";
  local dsk="$sqlookdir/sqlook.desktop";
  if [[ -e $png ]]; then
   unix sudoit cp -fvu "$png" /usr/share/pixmaps/;
   unix sudoit chmod -c ugo+r /usr/share/pixmaps/$(basename $png);
  fi;
  if [[ -e $dsk ]]; then
   unix sudoit cp -fvu "$dsk" /usr/share/applications/;
   unix sudoit chmod -c ugo+r /usr/share/applications/$(basename $dsk);
  fi;
 fi;
};

function firebird_desktop_menu(){
 copy_sqlook;
 local png="$scriptHOME/$scriptbase.png";
 local dsk="$scriptHOME/$scriptbase.desktop";
 if [[ -e $png ]]; then
  unix sudoit cp -fvu "$png" /usr/share/pixmaps/;
  unix sudoit chmod -c ugo+r /usr/share/pixmaps/$scriptbase.png;
 fi;
 if [[ -e $dsk ]]; then
  unix sudoit cp -fvu "$dsk" /usr/share/applications/;
  unix sudoit chmod -c ugo+r /usr/share/applications/$scriptbase.desktop;
 fi;
 if [[ -r /usr/share/pixmaps/$scriptbase.png ]] && [[ -r /usr/share/applications/$scriptbase.desktop ]]; then
  execute unix sudoit update-desktop-database;
 fi;
 make_dbsamples;
 copy_dbdrivers;
};

function firebird_desktop_drop(){
 if [[ -e /usr/share/pixmaps/$scriptbase.png ]] || [[ -e /usr/share/applications/$scriptbase.desktop ]]; then
  execute unix sudoit rm -fv /usr/share/pixmaps/$scriptbase.png /usr/share/applications/$scriptbase.desktop;
  execute sudo update-desktop-database;
 fi;
};

function run_flamerobin(){
 local dsk="/usr/share/applications/daqgroup-flamerobin.desktop";
 if [[ ! -r $dsk ]]; then dsk="/opt/daqgroup/share/flamerobin/addons/applications/daqgroup-flamerobin.desktop"; fi;
 if [[ -r $dsk ]] && execute xdg-open $dsk; then return; fi;
 execute unix grun flamerobin;
};

function run_foo(){
 local foo="$1";
 if [[ -z $foo ]]; then return; fi;
 if which $foo >/dev/null 2>&1; then
  local dsk="/usr/share/applications/$foo.desktop";
  if [[ -r $dsk ]] && execute xdg-open $dsk; then return; fi;
  execute unix grun $foo;
 else
  fatal 1 "Could not find $foo. Install it first.";
 fi;
};

function run_sqlectron(){
 run_foo sqlectron;
};

function run_antares(){
 run_foo antares;
};

function run_sqlook(){
 run_foo sqlook;
};

function main(){
 case $1 in
  --version)             show_vers; return 0; ;;
  -h|-help|--help)       show_help; return 0; ;;
  -l|-list|--list)       firebird_list; ;;
  -w|-which|--which)     firebird_which; ;; 
  -s|-status|--status)   firebird_control status; ;;
  -r|-restart|--restart) firebird_control restart; ;;
  -b|-start|--start)     firebird_control start; ;;
  -q|-stop|--stop)       firebird_control stop; ;;
  -i|-inst|--inst)       firebird_install; ;;
  -install|--install)    firebird_install; ;;
  -c|-client|--client)   firebird_client; ;;
  -u|-user|--user)       firebird_user; ;;
  -reconfig|--reconfig)  firebird_reconfig; ;;
  -m|-menu|--menu)       firebird_menu_cpl; ;;
  -d|--desktop-menu)     firebird_desktop_menu; ;;
  --desktop-drop)        firebird_desktop_drop; ;;
  --run-flamerobin)      run_flamerobin; ;;
  --run-sqlectron)       run_sqlectron; ;;
  --run-antares)         run_antares; ;;
  --run-sqlook)          run_sqlook; ;;
  --dbsamples)           make_dbsamples; ;;
  --dbdrivers)           copy_dbdrivers; ;;
  ''|*)                  colorize_head show_usage; ;;
 esac;
};

main "$@";

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