#!/bin/bash

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

########################
# Script identification.
########################
readonly startupdir="$(pwd -LP)";
readonly scriptfile="${BASH_SOURCE[0]}";
readonly scriptname="$(basename $scriptfile)";
readonly scriptbase="$(basename $scriptfile .sh)";
readonly scripthome="$(dirname  $scriptfile)";
readonly scriptFILE="$(realpath $scriptfile)";
readonly scriptHOME="$(dirname  $scriptFILE)";

declare -i nfail=0;
declare -i ndone=0;

function colorize_norm()( set -o pipefail; ( "$@" 2>&1>&3 | sed $'s,.*,\e[31m&\e[m,' >&2 ) 3>&1 | sed $'s,.*,\e[32m&\e[m,' );
function colorize_bold()( set -o pipefail; ( "$@" 2>&1>&3 | sed $'s,.*,\e[1;31m&\e[m,' >&2 ) 3>&1 | sed $'s,.*,\e[1;32m&\e[m,' );
function colorize_head()( set -o pipefail; ( "$@" 2>&1>&3 | sed $'s,.*,\e[1;35m&\e[m,' >&2 ) 3>&1 | sed $'s,.*,\e[1;37m&\e[m,' );

function split(){
 local line=""; local exitcode=0;
 while read -r line || [[ -n "$line" ]]; do
  local status=0;
  if [ "x${line/SUCCESS   : /}" != "x$line" ]; then let status=1; fi;
  if [ "x${line/BAD MD5   : /}" != "x$line" ]; then let status=2; fi;
  if [ "x${line/NOT FOUND : /}" != "x$line" ]; then let status=2; fi;
  if [ "x${line/checking result : FAILURE/}" != "x$line" ]; then let status=2; let exitcode=1; fi;
  if [ "x${line/checking result : SUCCESS/}" != "x$line" ]; then let status=1; let exitcode=0; fi;
  case $status in
   1) unix printc -c:+0a "$line" -c:0 -n; ;;
   2) unix printc -c:+0c "$line" -c:0 -n; ;;
   *) unix printc -c:+0f "$line" -c:0 -n; ;;
  esac;
 done;
 return $exitcode;
};

function test_checksum(){
 for dir in $*; do
  if unix checksum -b$dir | split; then let ndone++; else let nfail++; fi;
 done;
 if [ $nfail -eq 0 ]; then
  unix printc -n -n -c:+0a "$scriptname result: $ndone items done, $nfail items failed." -n -n -c:0;
 else
  unix printc -n -n -c:+0c "$scriptname result: $ndone items done, $nfail items failed." -n -n -c:0;
 fi;
};

function main(){
 if pushd $scriptHOME > /dev/null 2>&1; then
  if [ -t 1 ]; then
   test_checksum crwdaq crwlib crwkit;
  else
   exec xterm -fa 'PT Mono' -fs 12 -geometry 118x35+167+100 -hold -e "$scriptFILE";
  fi;
 fi;
 popd $scriptHOME > /dev/null 2>&1;
};

main "$@";

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