#!/bin/bash

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

###########################################################
## Utility to milliseconds since XMas: 0001.01.01-00:00:00.
###########################################################

# Unix Epoch 1970.01.01-00:00:00.
# sec. since 0001.01.01-00:00:00.
readonly UnixTimeBase="62135596800";

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 time, msec since XMas: 0001.01.01-00:00:00.";
 echo "Usage:";
 echo " $name [-options]";
 echo "Options:";
 echo " -h,--help   - print help.";
 echo " --version   - print version.";
 echo " -f,--float  - print as floating point";
 echo " -e,--epoch  - time since Unix epoch 1970.01.01-00:00:00.";
 echo " -b,--boot   - time since last boot (uptime -s)."
 echo "Examples:";
 echo " unix $name --help";
 echo " unix $name --version";
 echo " unix $name -f -e";
 echo " unix $name -b";
 echo " unix $name";
};

declare  -i opt_f=0;
declare TimeBase="$UnixTimeBase";

function boot_time(){
 date +%s.%N --date="$(uptime -s)";
};

function calc_msecnow(){
 echo "( $TimeBase + $(date +%s.%N) ) * 1000" | bc;
};

function print_msecnow(){
 local ms="$(calc_msecnow)";
 if [[ $opt_f -eq 0 ]]; then
  echo "${ms/.*/}";
 else
  echo "${ms:0: -3}";
 fi;
};

function main(){
 while [[ -n "$1" ]]; do
  case $1 in
   -version|--version) do_help 0; exit 0; ;;
   -h|-help|--help)    do_help 1; exit 0; ;;
   -f|-float|--float)  let opt_f=1; ;;
   -e|-epoch|--epoch)  TimeBase="0"; ;;
   -b|-boot|--boot)    TimeBase="-$(boot_time)"; ;;
   -*)                 fatal 1 "Error: unknown option: $1"; ;;
   *)                  fatal 1 "Error: unexpected argument: $1"; ;;
  esac;
  shift;
 done;
 print_msecnow;
};

main "$@";

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