#!/bin/bash

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

###########################################################
## Utility to print wanted file/directory location.
###########################################################

function fatal(){ echo -ne "\n$2\n\n"; exit $1; };

function do_help(){
 local name="$(basename ${BASH_SOURCE[0]})";
 echo "$name version 1.0";
 if [ $1 -eq 0 ]; then return 0; fi;
 echo "Copyright (c) 2002-2024 Alexey Kuryakin daqgroup@mail.ru";
 echo "$name - print location of wanted daqgroup files/directories.";
 echo "Usage:";
 echo " $name [-options] [arguments]";
 echo "Options:";
 echo " -h,--help   - print help.";
 echo " --version   - print version.";
 echo " -l,--list   - print list of available arguments.";
 echo "Arguments:";
 do_list;
 echo "Examples:";
 echo " unix $name --help";
 echo " unix $name --list";
 echo " unix $name --version";
 echo " unix $name dimsite";
 echo " unix $name smisite";
 echo " unix $name smiSM";
};

function do_list(){
 echo " dimsite     - print location of DIM site";
 echo " smisite     - print location of SMI site";
 echo " <name>      - print 'which <name>' or 'whereis <name>'";
};

declare -i deref=0;

function print_path(){
 local who="$1";
 if [[ -e "$who" ]]; then
  if [[ $deref -gt 0 ]]; then
   realpath "$who";
  else
   echo "$who";
  fi;
 else
  fatal 1 "Error: not found $who";
 fi;
};

function do_other(){
 exec unix whichis "$@";
 # obsolete version:
 local who="$(unix which $1)";
 if [[ -n "$who" ]]; then print_path "$who"; return 0; fi;
 who="$(whereis -b $1 | sed "s/.*://" | xargs | cut -f 1 -d ' ')";
 if [[ -n "$who" ]]; then print_path "$who"; return 0; fi;
 fatal 1 "Error: unknown entity: $1";
};

function main(){
 if [[ $# -eq 0 ]]; then
  fatal 1 "Error: missed arguments.\nType unix $(basename ${BASH_SOURCE[0]}) -h for help.";
 fi;
 while [[ -n "$1" ]]; do
  case $1 in
   -version|--version) do_help 0; exit 0; ;;
   -h|-help|--help)    do_help 1; exit 0; ;;
   -l|-list|--list)    do_list;   exit 0; ;;
   -L|--dereference)   let deref=1; shift; continue; ;;
   dimsite)            realpath -e $(dirname $(realpath $(unix which dimStat)))/../..; ;;
   smisite)            realpath -e $(dirname $(realpath $(unix which smiTrans)))/../..; ;;
   -*)                 fatal 1 "Error: unknown option $1."; ;;
   *)                  do_other "$@"; ;;
  esac;
  shift;
 done;
};

main "$@";

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