#!/bin/bash

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

###########################################################
## Run Python script/command in python virtual environment.
###########################################################

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

let fatal_notify_uses=0; # switch off notifications

###############################
# program constants & variables
###############################
readonly pyvenv_directory="/opt/daqgroup/share/pyvenv";
readonly pyvenv_bin_activate="$pyvenv_directory/bin/activate";

#####################
# print help on usage
#####################
function usage(){
 local name="$scriptname";
 echo "$name version 1.0 from 20250304";
 if [ "$1" = "0" ]; then return 0; fi;
 echo "Copyright (c) 2025 Alexey Kuryakin daqgroup@mail.ru";
 echo "$name: run command/script in python virtual environment.";
 echo "Usage:";
 echo " $name -h,--help    - show help";
 echo " $name --version    - show version";
 echo " $name -p,--path    - print path of virtual environment directory";
 echo "Examples:";
 echo " $name -p";
 echo " $name python3";
 echo " $name pip list";
 echo " $name script.py";
};

###################################
# print path of virtual environment
###################################
function pyvenv_print_path(){
 echo "$pyvenv_directory";
};

###############################
# activate virtual environment,
# then execute commandline "$@"
###############################
function pyvenv_exec(){
 if [[ -r $pyvenv_bin_activate ]]; then
  source $pyvenv_bin_activate;
  exec "$@";
 else
  fatal 1 "Error: not found $pyvenv_bin_activate";
 fi;
};

###############
# main function
###############
function main(){
 if [[ -z $1 ]]; then
  fatal 1 "Error: empty arguments. Type $scriptname -h for help.";
 fi;
 while [[ -n $1 ]]; do
  case $1 in
   -version|--version)    usage 0; return 0; ;;
   -h|-help|--help)       usage 1; return 0; ;;
   -p|-path|--path)       pyvenv_print_path; return 0; ;;
   -*)                    fatal 1 "Error: wrong option $1. Type $scriptname -h for help."; ;;
   *.py)                  pyvenv_exec python "$@"; return $?; ;;
   *)                     pyvenv_exec "$@"; return $?; ;;
  esac;
  shift;
 done;
};

main "$@";

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