#!/bin/sh

set +x
DEFUSER=alex
declare -i TRUE=0
# local TRUE=0
declare -i FALSE=1
# local FALSE=1

# source /mnt/rubis/home/alex/works/squashfs/set_BASEPATH

# files from 2 hosts considered same time 
MAXTIMEDIFF=5

# Conditional function definition 
if [ "z$(which usleep)" = "z" ]
then 
   usleep()
  {
  tutu=`expr $1 / 1000000`
  sleep $tutu
  }
fi

# signal, sometimes pcspeaker cannot be unmuted
makenoise()
{
# echo -e '\a'; usleep 100000 ; echo -e '\a'  
# aplay -q ${BASEPATH}/usr/share/sounds/speech-dispatcher/test.wav ; 
# ogg123 -q /usr/share/sounds/gnome/default/alerts/drip.ogg 2>&1 > /dev/null
# ogg123 /usr/share/sounds/freedesktop/stereo/window-question.oga 2>&1 > /dev/null
# usleep 10000 ; 
# usleep 100 ; 
#aplay ${BASEPATH}/usr/share/sounds/
 # if [ $(whoami) = root ]
 # then
 # mplayer -quiet -ao alsa:device=hw=1  /usr/share/sounds/KDE-Sys-Warning.ogg 2>&1 >/dev/null
 # else
 # mplayer -quiet -ao pulse::0 /usr/share/sounds/KDE-Sys-Warning.ogg 2>&1 >/dev/null
 # fi
# aplay --quiet /usr/share/sounds/GNUstep/Ping.wav -D sysdefault:CARD=PCH
# aplay --quiet /usr/share/sounds/GNUstep/Ping.wav
# aplay /usr/share/sounds/GNUstep/Ping.wav -D sysdefault:CARD=PCH # 2020-03-15-16:49  (See procedures.txt 2019-09-05-14:24)
# aplay --quiet /usr/share/sounds/GNUstep/Ping.wav -D sysdefault:CARD=PCH # 2020-03-15-16:49  (See procedures.txt 2019-09-05-14:24)
#  2>&1 > /dev/null
# aplay --quiet /usr/share/sounds/GNUstep/Ping.wav #  2>&1 > /dev/null
# play -q /usr/share/sounds/GNUstep/Ping.wav
# the following should work with or without X, with or without jack, with or without pulseaudio, but it does not
# aplay -q -D sysdefault:CARD=PCH /usr/share/sounds/GNUstep/Ping.wav
  # if [ $(whoami) = root ]
 # then
 # mplayer -quiet -ao alsa:device=hw=1  /usr/share/sounds/KDE-Sys-Warning.ogg 2>&1 >/dev/null
 # else
 # mplayer -quiet -ao pulse::0 /usr/share/sounds/KDE-Sys-Warning.ogg 2>&1 >/dev/null
 # fi
# aplay -q /usr/share/sounds/GNUstep/Ping.wav
which pulseaudio; wpulse=$?
which play; wplay=$?
if [[ $(whoami) != root && $wpulse == 0 ]]
then
    pulseaudio --check;
    if [ $? == 0 ];
    then
	ps aux | grep jackd | grep -v grep 2>&1 > /dev/null
	if [ $? == 0 ]; 
	then # pulseaudio and jackd running 
	    # mplayer -ao jack -volume 20 /usr/share/sounds/GNUstep/Ping.wav 2>&1 > /dev/null
	    aplay --quiet /usr/share/sounds/GNUstep/Ping.wav 
	else # pulseaudio running but not jackd 
	    aplay -q /usr/share/sounds/GNUstep/Ping.wav;
	fi			
    else # pulseaudio not running
	ps aux | grep jackd | grep -v grep 2>&1 > /dev/null
	if [ $? == 0 ]; 
	then # jackd  running but not pulseaudio
	    mplayer -ao jack -volume 20 /usr/share/sounds/GNUstep/Ping.wav 2>&1 > /dev/null
	else # nor pulseaudio nor jackd running
	    if [ $wplay == 0 ]
	    then play -q -v 0.5 /usr/share/sounds/GNUstep/Hero.wav -t alsa ; # pulseaudio not running
	    fi
	fi		
    fi
fi
}


makenoiseforever()
{
    while [ 0 -eq 0 ]; do makenoise; done
}

# give opportunity to read output
 hit()
{
 echo -e $*
 echo "Hit ENTER to continue"; 
 makenoise
 read ; 
}
# verbose only version
 vhit()
{
 if  [[ z"$verbose" = z"true" || z"$verbose" = z"TRUE"|| z"$verbose" = z"OUI" ]];
 then
   echo $*
   echo "Hit ENTER to continue"; 
   makenoise
   read ;
 fi
}
# debug only version
 debug_hit()
{
 if [ z$BASH_DEBUG != z ]
 then
   echo $*
   echo "Hit ENTER to continue"; 
   makenoise
   read ;
 fi
}

highline () # phrase color static
{
    #    echo "\$1" is $1
    # echo \$# is $#
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ||  -z "$1" ]]
    then
	line="highline phrase [color, static]"
	echo -e "${color}${On_Black}${line}${Color_Off}"
	return
    fi
    if [ -n "$3" ]
    then
	static="OUI"
    else
	static="NON"
    fi
    if [ -n "$2" ]
    then
	color="$2"
    else
	color="${BYellow}"
    fi
    if [ -n "$1" ]
    then
	line="$1"
    else
	line="Nothing to display"
    fi
    # echo -e "${color}${On_Black}${line}${Color_Off}"
    if [ $static == OUI ]
    then	# glitch with first character, sor we add a space
	echo -ne " ${color}${On_Black}${line}${Color_Off}\r"
    else
	echo -e "${color}${On_Black}${line}${Color_Off}"
    fi
    #        printf '%s\r' "${color}${On_Black}${line}${Color_Off}"
}


highline2 ()# phrase foreground background
{
# set background:
if [ -n "$3" ]
then
    bg="$3"
else
    bg="${On_Black}"
fi
# set foreground:
if [ -n "$2" ]
then
    fg="$2"
else
    fg="${BYellow}"
fi
if [ -n "$1" ]
then
    line="$1"
else
    line="Nothing to display"
fi
    echo -e "${fg}${bg}${line}${Color_Off}"
  }

write_avail ()
{
    index=$1
    vecho "in function write_avail, index is $index"
    drive=$2
    vecho "in function write_avail, drive is $drive"
    if [ "$drive" == "/" ]
    then
	dfline=$(\df -lBM | grep "% /$")
    else
	dfline=$(\df -lBM | grep "${index}")
    fi
    vecho dfline is $dfline
    dfavail=$(echo $dfline | awk '{print $4}')_free
    vecho dfavail is $dfavail
    line=$(echo $dfavail  | tr _ " ")
    echo -e "${BYellow}${On_Black}${line}${Color_Off}"
    # echo $dfavail  | tr _ " "
    if [ "$drive" == "/" ]
    then
	idfile=${drive}${index}_${dfavail}.txt
    else
	idfile=${drive}/${index}_${dfavail}.txt
    fi
    vecho idfile is $idfile
    sudo rm -f ${drive}/${index}*.txt
    # echo $dfline  > $idfile
    sudo sh -c "echo $dfline  > $idfile"
}

# question string is given as argument
# if a second argument "askit" equal to false is given, returns yes without asking.
source ${HOME}/.mycolors
y_or_n()
{
 if [[ z$2 = "zfalse" || z$2 = "zFALSE" || z$2 = "zNON" ]];
 then
  return 0
 fi
 REPLY=
#  until [ "z$REPLY" = "zy" ] || [ "z$REPLY" = "zn" ] || [ "z$REPLY" = "zyes" ] || [ "z$REPLY" = "zno" ] || [[ $(expr match "$REPLY" '[0-9]') -ge 1 ]]
 until [ "z$REPLY" = "zy" ] || [ "z$REPLY" = "zn" ] || [ "z$REPLY" = "zyes" ] || [ "z$REPLY" = "zno" ] 
 do 
# echo ${1}\?;
  makenoise
#  echo -e "${BYellow}${On_Black}${1}?${Color_Off}"
  echo -e "${BRed}${On_Gray}${1}?${Color_Off}"	
 echo Please answer y or n.
 read 
# REPLY=$(echo $REPLY | tr ' ' '_')
#  REPLY=$(echo $REPLY)
  REPLY=$(echo $REPLY | tr "[A-Z]" "[a-z]")
 echo REPLY is $REPLY
 done

if [[ $(expr match "$REPLY" '[yo]') -ge 1 ]]
 then
 # echo do it
  return 0
 else
 # echo don\'t do it
  return 3
 fi
}

yes_or_no()
{
 if [[ z$2 = "zfalse" || z$2 = "zFALSE" || z$2 = "zNON" ]];
 then
  return 0
 fi
 REPLY=
 until [ "z$REPLY" = "zyes" ] || [ "z$REPLY" = "zno" ] || [ "z$REPLY" = "zoui" ] || [ "z$REPLY" = "znon" ] 
 do 
# echo ${1}\?;
  makenoise
  echo -e "${BYellow}${On_Black}${1}?${Color_Off}"	
 echo Please answer yes/oui or no/non.
 read 
# REPLY=$(echo $REPLY | tr ' ' '_')
#  REPLY=$(echo $REPLY)
  REPLY=$(echo $REPLY | tr "[A-Z]" "[a-z]")
 echo REPLY is $REPLY
 done

if [[ $(expr match "$REPLY" 'yes') -ge 3 ]] || [[ $(expr match "$REPLY" 'oui') -ge 3 ]]
 then
 # echo do it
  return 0
 else
 # echo don\'t do it
  return 3
 fi
}

# ask for a string
# first arg is question
# second arg is default
gimme_a_string()
{
    default=$2
    REPLY=
    if  [ "z$default" != z ]
    then
	echo -e ${1}\? \(default  ${default}\);
	makenoise
	#   echo Please give me a string.
	read
	if [ "z$REPLY" == z ]	
	then REPLY=$default	
	     return
	fi
    else # we don’t want inadvertent short strings like y, n, yes, no, etc.
	while  [[ z$REPLY == z || ${#REPLY} < 4 ]]
	do 
	    echo -e ${1}\?;
	    makenoise
	    #   echo Please give me a string.
	    read
	done
    fi
}

# args are a question followed by the allowed answers
gimme_an_answer ()
{        
    if [ $# -lt 2 ];
    then echo "Function gimme_an_answer needs one question and at least one allowed answer.";
	 return 1;
    fi
    question=$1
    shift
    REPLY=
    accept=1
    until [ $accept -eq 0 ] 
    do 
	echo ${question}\?;
	makenoise
	echo Please give me an answer among: "$@"
	read
	for answer in "$@"; 
	do
	    if [ "z$answer" = "z$REPLY" ]
	    then
		accept=0
	    fi
	done
    done
}

# allowed_subdirs="/tmp ${HOME}/tmp"
# args are a question followed by the allowed answers
gimme_a_directory ()
{
    echo "Entering function gimme_a_directory ()"
    if [ $# -lt 3 ]
    then
    echo "Function gimme_a_directory needs at least one question, one parent directory and one allowed directory list.";
    	return 1;
    fi
    question=$1
    shift
    parentdir=$1
    shift
    allowed_subdirs=$@
    REPLY=
    accept=1
    y_or_n "Is the current default \"${chosendir}\" OK"
    if [ $? == 0 ] 
    then
	return 0
    fi
    until [ $accept -eq 0 ] 
    do 
#	echo "${question}"\?;
	makenoise
	echo "Please give me a directory among the following subdirs of ${SITEDIR}:" $allowed_subdirs;
	read 
	echo REPLY is $REPLY
	chosendir=$REPLY
	echo chosendir  is $chosendir
	for mydir in $allowed_subdirs
	do
	    echo mydir is $mydir
	    if [[ "$chosendir" == "$mydir" && -d "${SITEDIR}/$chosendir" ]]
	    then
		echo "Accepting ${chosendir}"
		accept=0
		return 0
	    fi
	done
	echo "Trying to set new not currently allowed directory $chosendir "
	setdir $chosendir
	if [ $? = 1 ]; then return 1; else accept=0; return 0; fi
    done
}

# chosendir is given as argument, it is a directory
setdir ()
{
    echo "Entering function setdir ()"
    echo "new directory is $@"
    mydir="${SITEDIR}/$@"
    echo "mydir is $mydir"
    if [ ! -d "${mydir}" ]
    then
	y_or_n "${mydir} is not a directory, do you want to create it?"
	if [ $? == 0 ] 
	then
	    mkdir "${mydir}"
	    if [ $? != 0 ]
	    then
		echo "${mydir} creation failed, exiting"; mydir=; return 1;
	    fi
	else
	    echo "${mydir} is not a directory, exiting"
	    mydir=; return 1;    
	fi
    fi
    return 0
}

debug_echo() # $*=blabla 
{
 # echo BASH_DEBUG = $BASH_DEBUG;
 # if [ z$BASH_DEBUG != z ]; then echo $* 1>&2 ; fi
 if [ z$BASH_DEBUG != z ]; then echo $* ; fi
}

isnumber() # $*=blabla 
{
 number=$1;
 number=${number##0x}
 number=${number##0X}	
 number=${number##0}
 #echo number = $number
 number=`echo $number | sed 's/[0-9]*//g'`
 number=`echo $number | sed 's/[A-F]*//g'`	
 #echo number = $number
 if [ -z $number ]; then testnb=true; else testnb=false; fi;
}

noroot()
{
 if [ $(whoami) = root ]
 then 
   if [ "z$1" != "z" ]
   then
	 echo $1
   else
	 echo "Please don\'t run this as root"
   fi
         return 0
 fi
}

beroot()
{
    if [ $(whoami) != root ]
    then 
	echo "You must be root to do this."
	return 1
    else
	return 0
    fi
}

pourdevrai()
{
if  [[ z"$testing" = "z" || z"$testing" = z"false" || z"$testing" = z"FALSE" || z"$testing" = z"NON" || z"$sandbox" = z"NON" ]]
then return 0  # pourdevrai true
else
return 1  # pourdevrai false
fi
}

showdo()
{
 showdocom="$*"
 echo -e "${BYellow}${On_Black}${showdocom}${Color_Off}"
 pourdevrai
 if  [ $? = 0 ]
 then
  echo case pourdevrai yes
  $showdocom
  return $?
else	
  echo case pourdevrai no
  return 0
 fi
}


showdo2()
{
 showdocom="$@"
 eval "echo $showdocom"
 pourdevrai
 if  [ $? = 0 ]
 then
  eval $showdocom
 fi
}


# 2018-05-18-15:05  amended, now seems to work
showdoask()
{
 showdocom="$*"
 echo $showdocom
 y_or_n "Do it"
 if [ $? = 0 ]
 then # echo Doing it
     pourdevrai
     if  [ $? = 0 ]
     then
      ret=$($showdocom) ; 
     else echo testing only; ret=0
     fi
     return $ret
 else echo Not doing it.
   return 1
 fi
}

showdoroot()
{
 showdocom="$*"
 echo $showdocom
 vecho "In showdoroot showdocom is $showdocom" 
 pourdevrai
 if  [ $? = 0 ]
 then
  if [ $(whoami) = root ]
  then
   $showdocom
  else
   su -m -c "$showdocom"
  fi
 fi
}

showdoaskroot()
{
 showdocom="$*"
 echo $showdocom
  y_or_n "Do it"
  if [ $? = 0 ]
  then # echo Doing it
    pourdevrai
    if  [ $? = 0 ]
    then 
      if [ $(whoami) = root ]
      then
       $showdocom
      else
       su -m -c "$showdocom"
      fi
    else  echo testing only; 
    fi
    return 0
  else echo Not doing it.
    return 1
  fi
}

vecho()
{
 if  [[ z"$verbose" = z"true" || z"$verbose" = z"TRUE"|| z"$verbose" = z"OUI" ]];
 then
   echo $*
 fi
}

# this one comments its output:
cvecho()
{
 if  [[ z"$verbose" = z"true" || z"$verbose" = z"TRUE"|| z"$verbose" = z"OUI" ]];
 then
   echo \# $*
 fi
}
# exit from script if the environment variable is not defined.
envassert()
{
 if [ "z${!1}" = "z" ]
 then
 echo "Environment variable $1 must be defined for this script to run."
 return 1
 fi
}


# exit if cd fails
safecd()
{
 cd $1
 if [ $? != 0 ]
 then echo "Could not change directory, exiting ..."  
 return 1 
 fi	
}
# echo '$0 ' is $0
# caller=$(basename $0)
# caller=$0
lastpasswdfile=$HOME/tmp/lastpasswd.txt
logpass()
{
echo caller is $caller
debug_echo "In logpass pass is $pass"
if [ z$pass = z ]
then
 logger -t $caller "$caller used no pass."
else
 echo $pass | gpg -e --default-recipient-self | gpg --enarmor > $lastpasswdfile
fi
# retrieve using
# cat $lastpasswdfile | gpg --dearmor | gpg -d 
}

# mycommand must be defined before
report ()
{
    ec=$1; vecho return value is $ec;
    vecho "In report(), mycommand is ${mycommand} "
    if [ $ec != 0 ]
    then echo "${mycommand} failed with error $ec";
    else echo "${mycommand} succeeded"; 
    fi
    return $ec;	
}
# diagnostic after report()
diagnostic ()
{
    ec=$1; vecho diagnostic for $ec;
    strict=$2
    if [ $ec != 0 ]
    then echo "${mycommand} failed with error $ec";
	 if [ $strict == 0 ]; then echo "Strict diagnostic failed"; return $ec; else echo "Non strict diagnostic failed, continuing "; return $ec;  fi
    else echo "${mycommand} succeeded"; 
    fi
}

askexitmode ()
{
echo "Type s to run ${HOME}/bin/rsync_logout in SANDBOX mode"
echo "Type r to run ${HOME}/bin/rsync_logout in REAL mode"
echo "Type c to continue backups"
echo "Type x to logout immediately"
read -n 1 ANSWER
case "$ANSWER" in
  "s" )
      echo "ANSWER is s, running ${HOME}/bin/rsync_logout in SANDBOX mode"
      ${HOME}/bin/rsync_logout -st
  ;;
  "r" )
      echo "ANSWER is r, running ${HOME}/bin/rsync_logout in REAL mode"
      ${HOME}/bin/rsync_logout -s
      ;;
  "c" )
      echo "ANSWER is c, continuing backups"
      run_autorcs
      run_persologoutp_perso
      run_persologoutp_video
      run_asym_bu_perso
      run_asym_bu_video
      run_operamail_bu_usb
      bu_encoding_data
      bu_essential_files
      ;;
  "x" )
      echo "ANSWER is x, no more backups"
      ;;
  * )
   echo "Not in database."
  ;;
esac
}

########################################################################
################# STRING REPLACEMENT IN BUNCH OF FILES #################
########################################################################
# See conveniente.txt 2019-11-28-00:10 
# ♥♥♥♥♥ Do not display filenames with no match, do not list C++ lines which are fully commented out:
# ock_nc_stdout str mygrep myfiles redir
ock_nc_stdout()
{
echo "Usage: $0 str mygrep myfiles redir"
echo "default: $0 FAKE_NOTETRACK_NB \"fgrep -n\" \"*.pro *.h *.c  *.cpp\" stdout"
if [ -z "$4" ]; then redir=stdout; else redir="$4"; fi
if [ -z "$3" ]; then myfiles="*.pro *.h *.c  *.cpp"; else myfiles=$3; fi
if [ -z "$2" ]; then mygrep="fgrep -n"; else mygrep=$2; fi
if [ -z "$1" ]; then str="FAKE_NOTETRACK_NB"; else str=$1; fi
echo "for myf in ${myfiles}; do result=$(cat $myf | ${mygrep} \"${str}\" | grep -v \"^[[:digit:]]*:[[:space:]]*//\");"
for myf in ${myfiles}; do result=$(cat $myf | ${mygrep} "${str}" | grep -v "^[[:digit:]]*:[[:space:]]*//"); if [ -n "$result" ]; then echo; line=$(ls -ltr $myf); echo -e "${BYellow}${On_Black}${line}${Color_Off}"; echo "$result"; fi; done > "$redir"
}

########################################################################
############################## AUTO MOUNT ##############################
########################################################################
# function automountrem ()
# {
#     mypartition=$(lsblk -o label | grep CRUZ)
#     if [ -n "${mypartition}" ]
#     then
#     	mounted=$(< /etc/mtab fgrep ${mypartition})
#     	echo mounted is "$mounted"
#     	if [ -n "$mounted" ]
#     	then
#     	    echo $mypartition is mounted
#     	else
#     	    echo $mypartition is NOT mounted
#     	    mount "/mnt/${mypartition}"
#     	    return	
#     	fi
#     fi
#     mypartition=$(lsblk -o label | grep SD)
#     if [ -n "${mypartition}" ]
#     then
#     	mounted=$(< /etc/mtab fgrep ${mypartition})
#     	echo mounted is "$mounted"
#     	if [ -n "$mounted" ]
#     	then
#     	    echo $mypartition is mounted
#     	else
#     	    echo $mypartition is NOT mounted
#     	    mount "/mnt/${mypartition}"
#     	    return	
#     	fi
#     fi
#     mypartition=$(lsblk -o label | grep KINGSTON)
#     if [ -n "${mypartition}" ]
#     then
#     	mounted=$(< /etc/mtab fgrep ${mypartition})
#     	echo mounted is "$mounted"
#     	if [ -n "$mounted" ]
#     	then
#     	    echo $mypartition is mounted
#     	else
#     	    echo $mypartition is NOT mounted
#     	    mount "/mnt/${mypartition}"
#     	    return	
#     	fi
#     fi
# }


# check first unit with matching labels to mount/unmount it (similar to ubuntu automount)
automountrem ()
{
#    mypartition=$(lsblk -o label | grep CRUZ)
    mypartition=$(lsblk -o label | grep -E 'CRUZ|SD|KINGST|VERBAT|VICTURE|Oakcastle|AGPTEK|U5-' | sed -n 1p)
    if [ -n "${mypartition}" ]
    then
    	mounted=$(< /etc/mtab fgrep ${mypartition})
    	echo mounted is "$mounted"
    	if [ -n "$mounted" ]
    	then
    	    echo "$mypartition is already mounted"
	    y_or_n "Unmount it"
	    if [ $? == 0 ]
	    then
		echo "Unmounting ${mypartition}"
		upumount "/mnt/${mypartition}"
	    else
		echo "Not doing it"
	    fi	    
    	else
    	    echo "$mypartition is NOT mounted"
	    y_or_n "Mount it"
	    if [ $? == 0 ]
	    then
		echo "Mounting ${mypartition}"
		mount "/mnt/${mypartition}"
	    else
		echo "Not doing it"
	    fi	    
    	    return	
    	fi
    else
	echo "No matching partition"
    fi
}

########################################################################
######################### -- AUTO MOUNT END -- #########################
########################################################################

########################################################################
################################ RSYNC #################################
########################################################################
rsyncig ()
{
    # mkdir -m 744 -p $2
    # /home/alex/bin/allow_edit -r $2
    rsync -vaiu --no-links --ignore-existing --exclude-from=/home/alex/etc/bu_excl_rsync "$1" "$2"
    # was "${@: -2}" "${@: -1}"
}
rsyncig_dryrun ()
{
    # highline "mkdir -m 744 -p $2"
    # echo "/home/alex/bin/allow_edit -r $2"
   # rsync -vainu --no-links --ignore-existing --exclude=rsync_backups/ --exclude=.saves/ --exclude=bucoded/ --exclude=.Trash/ --exclude=*.~* --exclude=*.*~ --exclude=*
    # highline rsync -vainu --no-links --ignore-existing --exclude-from=/home/alex/etc/bu_excl_rsync "$1" "$2"
    rsync -vainu --no-links --ignore-existing --exclude-from=/home/alex/etc/bu_excl_rsync "$1" "$2"
}
rsyncigsu ()
{
    sudo mkdir -m 744 -p $2
    sudo /home/alex/bin/allow_edit -r $2
    sudo rsync -vaiu --no-links --ignore-existing --exclude-from=/home/alex/etc/bu_excl_rsync "$1" "$2"
#"${@: -2}" "${@: -1}"
}
rsyncigsu_dryrun ()
{
    echo "sudo mkdir -m 744 -p $2"
    echo "sudo /home/alex/bin/allow_edit -r $2"
    sudo rsync -vainu --no-links --ignore-existing --exclude-from=/home/alex/etc/bu_excl_rsync "$1" "$2"
    #  "${@: -2}" "${@: -1}"
}
rsynciglk ()
{
    mkdir -m 744 -p $2
    # /home/alex/bin/allow_edit -r $2
    rsync -vaiu --ignore-existing --exclude-from=/home/alex/etc/bu_excl_rsync "$1" "$2"
    # was "${@: -2}" "${@: -1}"
}
rsynciglk_dryrun ()
{
    highline "mkdir -m 744 -p $2"
    # echo "/home/alex/bin/allow_edit -r $2"
    # rsync -vainu --ignore-existing --exclude=rsync_backups/ --exclude=.saves/ --exclude=bucoded/ --exclude=.Trash/ --exclude=*.~* --exclude=*.*~ --exclude=* "$1" "$2"
    rsync -vainu --ignore-existing --exclude-from=/home/alex/etc/bu_excl_rsync "$1" "$2"
}
rsynciglksu ()
{
    sudo mkdir -m 744 -p $2
    sudo /home/alex/bin/allow_edit -r $2
    sudo rsync -vaiu --ignore-existing --exclude-from=/home/alex/etc/bu_excl_rsync
"$1" "$2"
#"${@: -2}" "${@: -1}"
}
rsynciglksu_dryrun ()
{
    echo "sudo mkdir -m 744 -p $2"
    echo "sudo /home/alex/bin/allow_edit -r $2"
    sudo rsync -vainu --ignore-existing --exclude-from=/home/alex/etc/bu_excl_rsync "$1" "$2"
    #  "${@: -2}" "${@: -1}"
}

rsynclk ()
{
    mkdir -m 744 -p $2
    # /home/alex/bin/allow_edit -r $2
    rsync -vaiu --modify-window=3605 --exclude-from=/home/alex/etc/bu_excl_rsync "$1" "$2"
    # "${@: -2}" "${@: -1}"
}
rsynclk_dryrun ()
{
    echo "mkdir -m 744 -p $2"
    # echo "/home/alex/bin/allow_edit -r $2"
    rsync -vainu --stats --modify-window=3605 --exclude-from=/home/alex/etc/bu_excl_rsync "$1" "$2"
    # "${@: -2}" "${@: -1}"
}

rsynclknodir ()
{
    mkdir -m 744 -p $2
    # /home/alex/bin/allow_edit -r $2
    rsync -vlptgoDinu --exclude-from=/home/alex/etc/bu_excl_rsync "$1" "$2"
    # "${@: -2}" "${@: -1}"
}

rsynclknodir_dryrun ()
{
    echo "mkdir -m 744 -p $2"
    # echo "/home/alex/bin/allow_edit -r $2"
    rsync -vlptgoDinu --exclude-from=/home/alex/etc/bu_excl_rsync "$1" "$2"
    # "${@: -2}" "${@: -1}"
}


rsynclksu ()
{
    sudo mkdir -m 744 -p $2
    sudo /home/alex/bin/allow_edit -r $2
    sudo rsync -vaiu --exclude-from=/home/alex/etc/bu_excl_rsync "$1" "$2"
    #"${@: -2}" "${@: -1}"
}
rsynclksu_dryrun ()
{
    echo "sudo mkdir -m 744 -p $2"
    echo "sudo /home/alex/bin/allow_edit -r $2"
    sudo rsync -vainu --exclude-from=/home/alex/etc/bu_excl_rsync "$1" "$2"
    # "${@: -2}" "${@: -1}"
}
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# %%%%%%%%%%%%%%%%%%%%%%%%%%% -- RSYNC END -- %%%%%%%%%%%%%%%%%%%%%%%%%%%%
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

########################################################################
############################## 	PACKAGING ##############################
########################################################################
mvandmd ()
{
highline "APPNAME is $APPNAME"
highline "VERSION is $VERSION"
highline "FLAVOR is $FLAVOR"
highline "PACKBASE1 is $PACKBASE1"
highline "INSTALL_DIR is $INSTALL_DIR"
cd ~/works/cpp/Qt5/${APPNAME}-${VERSION}/${FLAVOR}/
mkdir -p package/${PACKBASE1}/DEBIAN
cd package/${PACKBASE1}
}

karakb_pack ()
{
DEFAULT_VERSION=0.52
DEFAULT_FLAVOR_SUFFIX=demo
if [[ "$1" = -h  || "$1" = --help || "$1" = "?" ]]
then
highline "Usage: ${FUNCNAME[0]} version (default $DEFAULT_VERSION) flavor_suffix (default $DEFAULT_FLAVOR_SUFFIX)"
return
fi
APPNAME=karakb # ${APPNAME}
if [ -z "$2" ]
then
FLAVOR="qt5-$DEFAULT_FLAVOR_SUFFIX" # ${FLAVOR}
else
FLAVOR="qt5-$2" # ${FLAVOR}
fi
if [ -z "$1" ]
then
VERSION=$DEFAULT_VERSION # ${VERSION} # new version
else
VERSION="$1" # ${VERSION}
fi
PACKBASE1=${APPNAME}-${FLAVOR}_${VERSION}_amd64 # ❤❤❤❤❤
INSTALL_DIR=/usr
highline "update_dist /home/alex/works/cpp/Qt5 karakb ${FLAVOR} 0.51 0.52   '2023-06-15' '2023-07-24' 'version 0.51, June 15, 2023' 'version 0.52, July 24, 2023'" "${BGreen}"
mvandmd
}

xlocate_pack ()
{
DEFAULT_VERSION=0.82
DEFAULT_FLAVOR_SUFFIX=dist
if [[ "$1" = -h  || "$1" = --help || "$1" = "?" ]]
then
highline "Usage: ${FUNCNAME[0]} version (default $DEFAULT_VERSION) flavor_suffix (default $DEFAULT_FLAVOR_SUFFIX)"
return
fi
APPNAME=xlocate # ${APPNAME}
if [ -z "$2" ]
then
FLAVOR="qt5-$DEFAULT_FLAVOR_SUFFIX" # ${FLAVOR}
else
FLAVOR="qt5-$2" # ${FLAVOR}
fi
if [ -z "$1" ]
then
VERSION=$DEFAULT_VERSION # ${VERSION} # new version
else
VERSION="$1" # ${VERSION}
fi
PACKBASE1=${APPNAME}-${FLAVOR}_${VERSION}_amd64 # ❤❤❤❤❤
INSTALL_DIR=/usr

highline "update_dist /home/alex/works/cpp/Qt5 ${xlocate} FLAVOR 0.80 0.81 '2023-04-18' '2023-06-14' 'version 0.80, April 18, 2023' 'version 0.81, June 14, 2023'" "${BGreen}"
mvandmd
}

# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# %%%%%%%%%%%%%%%%%%%%%%%%% -- 	PACKAGING END -- %%%%%%%%%%%%%%%%%%%%%%%%%
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# BEGIN This is for info only, use xlocate_pack
# APPNAME=karakb # ${APPNAME}
# VERSION=0.52 # ${VERSION} # new version
# FLAVOR=qt5-demo # ${FLAVOR}
# PACKBASE1=${APPNAME}-${FLAVOR}_${VERSION}_amd64 # ❤❤❤❤❤
# INSTALL_DIR=/usr
# #update_dist /home/alex/works/cpp/Qt5 karakb ${FLAVOR} 0.51 0.52   '2023-06-15' '2023-07-24' 'version 0.51, June 15, 2023' 'version 0.52, July 24, 2023' 
# cd ~/works/cpp/Qt5/${APPNAME}-${VERSION}/${FLAVOR}
# mkdir -p package/${PACKBASE1}/DEBIAN
# cd package/${PACKBASE1}	
# END This is for info only, use xlocate_pack



# APPNAME=karakb # ${APPNAME}
# VERSION=0.52 # ${VERSION} # new version
# FLAVOR=qt5-demo # ${FLAVOR}
# PACKBASE1=${APPNAME}-${FLAVOR}_${VERSION}_amd64 # ❤❤❤❤❤
# INSTALL_DIR=/usr
# #update_dist /home/alex/works/cpp/Qt5 karakb ${FLAVOR} 0.51 0.52   '2023-06-15' '2023-07-24' 'version 0.51, June 15, 2023' 'version 0.52, July 24, 2023' 
# cd ~/works/cpp/Qt5/${APPNAME}-${VERSION}/${FLAVOR}
# mkdir -p package/${PACKBASE1}/DEBIAN
# cd package/${PACKBASE1}

# APPNAME=xlocate # ${APPNAME}
# VERSION=0.81 # ${VERSION}
# FLAVOR=qt5-dist # ${FLAVOR}
# PACKBASE1=${APPNAME}-${FLAVOR}_${VERSION}_amd64 # ❤❤❤❤❤
# INSTALL_DIR=/usr
# # update_dist /home/alex/works/cpp/Qt5 ${xlocate} FLAVOR 0.80 0.81 '2023-04-18' '2023-06-14' 'version 0.80, April 18, 2023' 'version 0.81, June 14, 2023'
# cd ~/works/cpp/Qt5/${APPNAME}-${VERSION}/${FLAVOR}/
# mkdir -p package/${PACKBASE1}/DEBIAN
# cd package/${PACKBASE1}

# The following commented out stuff is not required anymore
# In case it is necessary to do manually (just give actual directories for fr doc to .pro file) :
# alex@Freesia:~/works/cpp/Qt5/karakb-0.51$  NO sudo cp doc/en/HTML/*.html  /home/alex/LINUX_QT5/${APPNAME}-${VERSION}/${FLAVOR}/package/${PACKBASE1}/usr/doc/${APPNAME}/en	
# alex@Freesia:~/works/cpp/Qt5/karakb-0.51$  NO sudo cp doc/en/HTML/*.png /home/alex/LINUX_QT5/${APPNAME}-${VERSION}/${FLAVOR}/package/${PACKBASE1}/usr/doc/${APPNAME}/en	

# alex@Freesia:~/works/cpp/Qt5/karakb-0.51$ ?? sudo cp doc/en/OTP/target/*.html  /home/alex/LINUX_QT5/${APPNAME}-${VERSION}/${FLAVOR}/package/${PACKBASE1}/usr/doc/${APPNAME}/fr	
# alex@Freesia:~/works/cpp/Qt5/karakb-0.51$ ?? sudo cp doc/fr/HTML/*.png /home/alex/LINUX_QT5/${APPNAME}-${VERSION}/${FLAVOR}/package/${PACKBASE1}/usr/doc/${APPNAME}/fr	


# 2023-08-16-17:50
# find $str only outside of comments
letsfind () # defined in interact
{
for myf in ${myfiles}; do result=$(cat $myf | ${MYGREP} "${str}" | grep -v "^[[:digit:]]*:[[:space:]]*${cmt}"); if [ -n "$result" ]; then echo; line=$(ls -ltr $myf); echo -e "${BYellow}${On_Black}${line}${Color_Off}"; echo "$result";fi;  done
}

# exclude debugging command MYDEBUG
letsfinddeb ()
{
for myf in ${myfiles}; do result=$(cat $myf | ${MYGREP} "${str}" | grep -v "^[[:digit:]]*:[[:space:]]*${cmt}" | grep -v MYDEBUG); if [ -n "$result" ]; then echo; line=$(ls -ltr $myf); echo -e "${BYellow}${On_Black}${line}${Color_Off}"; echo "$result";fi;  done
}

# find $str inside or outside comments, don’t exclude any line
letsfindcom ()
{
for myf in ${myfiles}; do result=$(cat $myf | ${MYGREP} "${astr}"); if [ -n "$result" ]; then echo; line=$(ls -ltr $myf); echo -e "${BYellow}${On_Black}${line}${Color_Off}"; echo "$result"; fi; done
}

# replace $str with $newstr only outside of comments
letsrep ()
{
for myf in ${myfiles}; do result=$(cat $myf | ${MYGREP} "${str}" | grep -v "^[[:digit:]]*:[[:space:]]*${cmt}"); if [ -n "$result" ]; then echo; line=$(ls -ltr $myf); echo -e "${BYellow}${On_Black}${line}${Color_Off}"; echo "$result"; sed -i "s/\b${str}\b/${newstr}/g" "$myf"; fi;  done
}

# same as letsrep with debugging info:
letsrepverb ()
{
for myf in ${myfiles}; do result=$(cat $myf | ${MYGREP} "${str}" | grep -v "^[[:digit:]]*:[[:space:]]*${cmt}"); echo result is "$result"; if [ -n "$result" ]; then echo; line=$(ls -ltr $myf); echo -e "${BYellow}${On_Black}${line}${Color_Off}"; echo myf is "$myf"; echo line is "$line";  echo sed -i "s/${str}/${newstr}/g" "$myf"; sed -i "s/${str}/${newstr}/g" "$myf"; fi;  done
# discard $cmt and MYDEBUG
}



# downcase filename OK
# function downcase_JPG_cwd
# {
# for fi in *.JPG; do mv ${fi} $(echo $fi | tr 'A-Z' 'a-z'); done
# }

downcase_cwd ()
{
if [ -n "$1" ]; then MYEXT="$1"; else MYEXT="JPG"; fi
for fi in *.${MYEXT}; do mv ${fi} $(echo $fi | tr 'A-Z' 'a-z'); done
}

upcase_cwd ()
{
if [ -n "$1" ]; then MYEXT="$1"; else MYEXT="jpg"; fi
for fi in *.${MYEXT}; do mv ${fi} $(echo $fi | tr 'a-z' 'A-Z'); done
}

# makenoise()
# {
#  echo makenoise
# }

# makenoiseforever()
# {
#  echo coucou
# }


samefiles() 
{
if [[ -z "$1" || -z "$2" ]]; then echo Usage: samefiles file1 file2; return; fi
if [[ ! -e  "$1" ]]; then echo $1 does not exist; return; fi
if [[ ! -e  "$2" ]]; then echo $2 does not exist; return; fi
if [[ ! -s  "$1" ]]; then echo $1 is zero size; return; fi
if [[ ! -s  "$2" ]]; then echo $2 is zero size; return; fi
echo -n "${1}: "
r1=$(echo $(ls -Ldi $1) |  awk '{print $1}')
echo r1 is $r1 
echo -n "${2}: "
r2=$(echo $(ls -Ldi $2) |  awk '{print $1}')
echo r2 is $r2
if [ $r1 -eq $r2 ]
then echo Files are one and the same.
else echo Files have different inodes.
fi
# ls -Ldi $1 $2
}

samefiles2() 
{
if [[ -z "$1" || -z "$2" ]]; then echo Usage: samefiles file1 file2; return; fi
if [[ ! -e  "$1" ]]; then echo $1 does not exist; return; fi
if [[ ! -e  "$2" ]]; then echo $2 does not exist; return; fi
if [[ ! -s  "$1" ]]; then echo $1 is zero size; return; fi
if [[ ! -s  "$2" ]]; then echo $2 is zero size; return; fi
r1=$(echo $(ls -Ldi $1) |  awk '{print $1}')
r2=$(echo $(ls -Ldi $2) |  awk '{print $1}')
if [ $r1 -eq $r2 ]
then echo ONE
else echo TWO
fi
# ls -Ldi $1 $2
}

invertargs ()
{
echo -n $1 $3 $2
shift 3
echo $*
}

addlocation ()
{
mv ${2} ${1}-${2}
}


function ctrl_c() {
    echo "Ctrl + C happened"
    goon=1
#     return
}

# From https://superuser.com/questions/611538/is-there-a-way-to-display-a-countdown-or-stopwatch-timer-in-a-terminal
countdown() {
    goon=0
    if [ -z "$1" ]
    then
	highline "Please specify time to count down" "${BRed}"
	return
    fi    
    if [ -n "$2" ]
    then
	color="$2"
    else
	color="${BGreen}"
    fi

    trap ctrl_c INT

    if [ "$1" -eq 0 ]
    then
	start="$(( $(date '+%s')))"
	while [ $goon -eq 0 ]; do	
            time="$(( $(date +%s) - $start ))"		
	    # printf '%s\r' "$(date -u -d "@$time" +%H:%M:%S)	"	
            highline "$(date -u -d "@$time" +%M:%S)" "${color}" "static"
            # sleep 0.1
	done
    else
	start="$(( $(date '+%s') + $1))"
	while [ $start -ge $(date +%s) ]; do	
            time="$(( $start - $(date +%s) ))"		
	    # printf '%s\r' "$(date -u -d "@$time" +%H:%M:%S)	"	
            highline "$(date -u -d "@$time" +%M:%S)" "${color}" "static"
            # sleep 0.1
	done
    fi
}




stopwatch() {
    start=$(date +%s)
    while true; do
        time="$(( $(date +%s) - $start))"	
#        printf '%s\r' "$(date -u -d "@$time" +%H:%M:%S	)"
       	highline  "$(date -u -d "@$time" +%M:%S)" "${BGreen}"		
        sleep 0.1
    done
}
recordtitles_usg () 
{
    highline "Usage: recordtitles [directory, extension, duration]"
    highline "Records titles for all audio files in directory given as 1st argument (default \$PWD)."
    highline "Extension (default mp3) and duration (default 4s) can be specified as 2nd and 3rd arguments"
}

recordtitles () # [directory, extension, duration]
{
    if [ $# -gt 3 ]
    then
	recordtitles_usg 
	return 1
    fi
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	recordtitles_usg 
	return 1
    fi
    if [ -n "$3" ]
    then
	duration="$3"
    else
	duration=0
    fi
    if [ -n "$2" ]
    then
	extension="$2"
    else
	extension="mp3"
    fi
	  if [ -n "$1" ]
    then
	workingdir="$1"
    else
	workingdir="."
    fi
    rm -f *-title-title.*
    # rm -f *-title.*
    highline "duration is $duration"
    highline "extension is $extension"
    highline "workingdir is $workingdir"
    cd "${workingdir}"
    #    orderedfiles=$(echo "*.${extension}" | sort -n)    
    #   for soundfile in $(echo "*.${extension}" | sort -n)
    for soundfile in *.${extension}
    do
	if [[ ! "$soundfile" =~ "-title.${extension}" && ! -f ${soundfile%.*}-title.${extension} ]]
	then
	    highline2 "Recording title for " ${Red} ${On_White}
	    highline2 "$soundfile" 
	    # arecord -f cd -d "$duration" /mnt/endive4/tmp/test.wav &
	    arecord -c 1 -d "$duration" /mnt/endive4/tmp/test.wav & # man arecord says "A value of zero means infinity."
	    # if [ duration -ne 0 ];
	    # then
	    countdown "$duration" "${BGreen}";
	    # else
	    # ...
	    # fi
	    # arecord -f cd  ~/tmp/test.wav
	    # lame -V 2 --clipdetect /mnt/endive4/tmp/test.wav  "${soundfile%.*}"-title.mp3
	    lame -f -m m -b 128 /mnt/endive4/tmp/test.wav  "${soundfile%.*}"-title.mp3
	else
	    echo "$soundfile is a title or title already exists"
	fi   
    done
    # Now diving into subdirectories
    for mydir  in *
    do
	if [ -d  "$mydir" ]
	then
	    recordtitles "$mydir" $extension $duration
	fi
    done
    cd "${OLDPWD}"
}

recordtitles_1stlevel_usg () 
{
    highline  "Usage: recordtitles_1stlevel [extension, duration]"
    highline "Function recordtitles_1stlevel takes 2 mandatory parameters, extension (without dot) and duration (in seconds).";

    highline "Records titles using recortitles function for all subdirectories of \$PWD."
    highline "Extension and duration must be specified in command line"
}

recordtitles_1stlevel () # extension duration
{
    if [ $# -ne 2 ]
    then
	recordtitles_1stlevel_usg
    	return 1;
    fi
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	recordtitles_1stlevel_usg
	return 1
    fi
    extension="$1"
    duration="$2"
    for zicdir in *
    do
	if [ -d "$zicdir" ]
	then
	    recordtitles "$zicdir" ${extension} ${duration}
	fi
    done    
}

checktitles_usg ()
{
   highline "Usage checktitles [directory, extension]"
   highline2 "Scan current directory for audio files with not spoken title as recorded e.g. in recordtitles function."
   highline2 "subdirectories are just searched with find."
}

checktitles () # [directory, extension]
{
    if [ $# -gt 2 ]
    then
	checktitles_usg 
	return 1
    fi
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	checktitles_usg
	return
    fi
    if [ -n "$2" ]
    then
	extension="$2"
    else
	extension="mp3"
    fi
    if [ -n "$1" ]
    then
	workingdir="$1"
    else
	workingdir="."
    fi	  
    echo extension is $extension
    echo workingdir is $workingdir
    for md in "${workingdir}"/* ;
    do
	echo "md is $md"
	if [ ! -d "$md" ];
	then echo $md is not a directory;
	     fn=${md%.*}
	     echo fn is "$fn"
	     ext=${md##*.}
	     echo ext is "$ext"
	     # if [[ ! "$md" =~ ".${extension}$" ]]
	     # then
	     # 	 echo "Skipping non ${extension} file $md"
	     # fi
	     # if [[ ! "$md" =~ "-title.${extension}$" ]]
	     # then
	     # 	 echo "$md is not a title, skipping";
	     # 	 highline2 "$md has no title" ${BWhite} ${On_Red};
	     # 	 continue;
	     # else
	     # fi
	     if [[ "${ext}" != "${extension}" ]]
	     then
	     	 echo "Skipping wrong extension for file $md"
		 continue
	     fi
	     if [[ "${fn}" =~ "-title" ]]
	     then
	     	 echo "Skipping already recorded title $md"
		 continue
	     fi
	     if [ -f "${fn}-title.${ext}" ]
	     then highline "$md has a title";
	     else
		 highline2 "$md has no title" ${BWhite} ${On_Red};
	     fi;
	else
	    # md is a directory
	    echo $md is a directory;
	    mn=$(find "$md" -mindepth 0 -name "*-title*" | wc -l);
	    echo mn is $mn
	    mm=$(find "$md" -mindepth 0 -name "*.${extension}" | wc -l);
	    echo mm is $mm
	    if [[ $mn -gt 0 ]];
	    then highline "$md has $mn titles and $mm ${extension} files ";
	    else highline2 "$md has no titles" ${BWhite} ${On_Red};
	    fi;
	fi
	echo
    done
}

checktitles2_usg ()
{
   highline "Usage checktitles [directory, extension]"
   highline2 "Scan current directory and subdirectories for audio files with not spoken title as recorded e.g. in recordtitles function."
   
}

checktitles2 () # [directory, extension]
{
    if [ $# -gt 2 ]
    then
	checktitles2_usg 
	return 1
    fi
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	checktitles2_usg
	return
    fi
    if [ -n "$2" ]
    then
	extension="$2"
    else
	extension="mp3"
    fi
    if [ -n "$1" ]
    then
	workingdir="$1"
    else
	workingdir="."
    fi	  
    echo extension is $extension
    echo workingdir is $workingdir
    for md in "${workingdir}"/* ;
    do
	echo "md is $md"
	if [ ! -d "$md" ];
	then echo $md is not a directory;
	     fn=${md%.*}
	     echo fn is "$fn"
	     ext=${md##*.}
	     echo ext is "$ext"
	     # if [[ ! "$md" =~ ".${extension}$" ]]
	     # then
	     # 	 echo "Skipping non ${extension} file $md"
	     # fi
	     # if [[ ! "$md" =~ "-title.${extension}$" ]]
	     # then
	     # 	 echo "$md is not a title, skipping";
	     # 	 highline2 "$md has no title" ${BWhite} ${On_Red};
	     # 	 continue;
	     # else
	     # fi
	     if [[ "${ext}" != "${extension}" ]]
	     then
	     	 echo "Skipping wrong extension for file $md"
		 continue
	     fi
	     if [[ "${fn}" =~ "-title" ]]
	     then
	     	 echo "Skipping already recorded title $md"
		 continue
	     fi
	     if [ -f "${fn}-title.${ext}" ]
	     then highline "$md has a title";
	     else
		 highline2 "$md has no title" ${BWhite} ${On_Red};
	     fi;
	else
	    # md is a directory
	    echo $md is a directory;
	    cd "$md"
	    checktitles2
	    cd ..
	fi
	echo
    done
}

puttitlesback_usg ()
{
    echo ls "${targetpath}/${masterdir}"
    echo "3 optional arguments walkdir targetpath masterdir"
}

puttitlesback () # [ walkdir targetpath masterdir ]
{
    if [[ $# -gt 3 ]]
    then
	puttitlesback_usg
    	return 1;
    fi
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	puttitlesback_usg
	return 0
    fi
    targetpathdef=/COLLECS_ENDIVE2/p2p/Completed
    walkdirdef=.
    masterdirdef=$(basename "$PWD")
    if [ -n "$3" ]
    then
	masterdir="$3"
	targetpath="$2"
	walkdir="$1"
    elif [ -n "$2" ]
    then
	 targetpath="$2"
	 walkdir="$1"
	 masterdir="$walkdir"
    elif [ -n "$1" ]
    then
	 targetpath="$targetpathdef"
	 walkdir="$1"
	 masterdir=$(basename "$PWD")
    else
	targetpath="$targetpathdef"
	 walkdir="$walkdirdef"
	 masterdir=$(basename "$PWD")
    fi	 
    #masterdir="Mozart Requiem K.626 - Harnoncourt 2004"/
    echo sandbox is $sandbox
    if [ sandbox == OUI ]
    then MYRSYNC=rsyncig_dryrun
    else
	MYRSYNC=rsyncig
    fi
    for mf in "${walkdir}/"*-title.mp3 ;
    do
	highline2 "$MYRSYNC \"$mf\" \"${targetpath}\"/\"${masterdir}\"/"	      
	$MYRSYNC "$mf" "${targetpath}"/"${masterdir}"/ ;
    done
}

# recordtitles2 () # [duration, pattern]
# {
#     if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
#     then
# 	highline "recordtitles [duration, pattern]"
# 	return
#     fi
#     if [ -n "$2" ]
#     then
# 	pattern="$2"
#     else
# 	pattern="*.mp3"
#     fi
#     if [ -n "$1" ]
#     then
# 	duration="$1"
#     else
# 	duration="5"
#     fi
#     rm -f *-title-title.*
#     #    rm -f *-title.*
# #    highline "duration is $duration"
# #    highline "extension is $extension"
#     #    highline "workingdir is $workingdir"
#     workingdir=$(dirname "${pattern}")
#     cd "${workingdir}"
#     #    orderedfiles=$(echo "*.${extension}" | sort -n)    
#     #   for soundfile in $(echo "*.${extension}" | sort -n)
#     for soundfile in ${pattern}
#     do
# 	highline soundfile is $soundfile
# 	#    highline "$soundfile"
# 	if [[ ! "$soundfile" =~ "-title" && ! -f ${soundfile%.*}-title.* ]]
# 	then
# 	    highline "Working on $soundfile"
# 	    arecord -f cd -d "$duration" ~/tmp/test.wav &
# 	    countdown "$duration" "${BGreen}"
# 	    # arecord -f cd  ~/tmp/test.wav
# 	    lame --clipdetect ~/tmp/test.wav  "${soundfile%.*}"-title."${soundfile##*.}"
# 	else
# 	    echo "$soundfile is a title or title already exists"
# 	fi   
#     done
# cd ${OLDPWD}
# }

# Windows (FAT32, NTFS): Any Unicode except NUL : * ? " < > | . 
# Also, no space character at the start or end, and no period at the end.
vfatize () # [directory, extension, duration]
{
    if [ $# -ne 1 ]
    then
	echo "vfatise just takes a string as argument.";
	return 1;
    fi
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	highline "Modify string so that it can be a VFAT filename"
	return
    fi
    e2name=$1
    #    echo "${e2name}" | sed 's/\x00/@/g; s/\,/@/g; s/\:/@/g; s/\*/@/g; s/\"/@/g; s/</@/g; s/>/@/g; s/|/@/g; s/\.$/@/g;' | sed 's/^ /@/g;' | sed 's/ $/@/g;' # OK
        echo "${e2name}" | sed 's/\x00/@/g; s/\:/@/g; s/\?/@/g; s/\*/@/g; s/\"/@/g; s/</@/g; s/>/@/g; s/|/@/g; s/\.$/@/g;' | sed 's/^ /@/g;' | sed 's/ $/@/g;' # OK

# try with e2name=".2008 Haydn, Bee:thov?e\"n (Bo|rod<in Qu>a*rtet)."
# $user> vfatize "$e2name"
    # @2008 Haydn@ Bee@thov?e@n (Bo@rod@in Qu@a@rtet)@
    # see conveniente.txt:2023-08-12-19:52 for use cases
}

vfatcompliant () # ext2 file name
{
    if [ $# -ne 1 ]
    then
	echo "vfatise just takes a string as argument.";
	return 1;
    fi
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	highline "Modify string so that it can be a VFAT filename"
	echo "for mv in *.mp3 ; do vfatcompliant $mf; done"
	return
    fi
    e2name=$1
    echo e2name is ${e2name}; 
    vfatname=$(vfatize "${e2name}")
    echo vfatname is ${vfatname};
    if [ "${vfatname}" == "${e2name}" ]
    then echo "No change necessary to ${e2name} for vfat"
    else echo "${e2name} must be modified to be vfat compliant"
	 echo "suggest ${vfatname}"
    fi
}


# 2024-03-23-20:51 
# Convert flac to mp3 directly to target SD/stick
# Before calling cd to the HD dir containing flac files, namely $flacdir
flac2mp3 () # e.g. "/mnt/SDM32_05/collecs/Zique/Classic"
{
    if [[ $# -eq 2 && "$1" == "--no-image" ]];
    then echo "no image will be copied.";
	 noimage=OUI;
	 mytarget="$2"
    elif [ $# -eq 1 ];
    then echo "It will be asked for images to be copied.";
	 noimage=NON;
	 mytarget="$1"
    else
	echo "Function flac2mp3 needs one mandatory argument top directory target, evt preceded by --no-image to avoid questioning.";
	return 1;
    fi
    if [[ "$mytarget" =~ "-help" || "$mytarget" =~ "--help" || "$mytarget" =~ "-h" ]]
    then
	highline "Build mp3’s from all flac’s in cwd make a subdir of target dir and put them in it."
	highline2 "Obsolete, use lossless2mp3 instead, which also works with ape files" ${BWhite} ${On_Red}
	return
    fi
    someflacs=$(find . -maxdepth 1 -iname "*.flac")
    if [ -z "${someflacs}" ]
    then
	echo "No flac files found in current directory"
	return 1
    fi
    if [[ ! -e  "$mytarget" || ! -d  "$mytarget" || ! -w  "$mytarget" ]]; then echo "$mytarget" is not a valid target; return 1; fi
    targetdir="$mytarget"
    flacdir=$(basename "${PWD}")
    # vfatize directory name:
    targetsubdir=$(vfatize "${flacdir}")
    mkdir -p "${targetdir}/${targetsubdir}"
    #    for flacfile in *.flac; do ffmpeg -i "$flacfile" -ab 320k -map_metadata 0 -id3v2_version 3 "${targetdir}/${targetsubdir}/${flacfile%.*}.mp3"; done
    # Don’t forget to vfatize flac file names:
    for flacfile in *.flac;
    do vfatflacfile0="${flacfile%.*}.mp3"; vfatflacfile=$(vfatize "${vfatflacfile0}"); ffmpeg -i "$flacfile" -ab 320k -map_metadata 0 -id3v2_version 3 "${targetdir}/${targetsubdir}/${vfatflacfile}";
    done
    # for pic in *.jpeg;
    if 	 [ "$noimage" == NON ];
    then
	for pic in *.{jpg,jpeg};
	do
    	    y_or_n "Copy ${pic}"
    	    if [ $? == 0 ]
    	    then
    		highline "Copying ${pic}"
    		cp "${pic}" "${targetdir}/${targetsubdir}/${vfatmp3file}"
    	    else
    		highline "Not copying ${pic}"
    	    fi	
	done
    fi    
}

# 2024-03-23-20:51 
# Convert lossless to mp3 directly to target SD/stick
# Before calling cd to the HD dir containing lossless files, namely $losslessdir
lossless2mp3 () # e.g. "/mnt/SDM32_05/collecs/Zique/Classic"
{
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	highline "Build mp3’s from all lossless’s in cwd make a subdir of target dir and put them in it."
	return
    fi
    if [[ ! -e  "$1" || ! -d  "$1" || ! -w  "$1" ]];
    then echo "$1" is not a valid target; return 1;
    else
	targetdir="$1"
    fi
    if [ $# -ne 1 ]
    then
	echo "lossless2mp3 just takes a top directory target as argument.";
	return 1;
    fi
    someflacs=$(find . -maxdepth 1 -iname "*.flac")
    if [ -z "${someflacs}" ]
    then
	echo "No flac files found in current directory"
    else
	losslessdir=$(basename "${PWD}")
	# vfatize directory name:
	targetsubdir=$(vfatize "${losslessdir}")
	mkdir -p "${targetdir}/${targetsubdir}"
	# Don’t forget to vfatize lossless file names:
	for flacfile in *.flac;
	do
	    vfatflacfile0="${flacfile%.*}.mp3"; vfatflacfile=$(vfatize "${vfatflacfile0}"); ffmpeg -i "$flacfile" -ab 320k -map_metadata 0 -id3v2_version 3 "${targetdir}/${targetsubdir}/${vfatflacfile}";
	done
    fi
    someapes=$(find . -maxdepth 1 -iname "*.ape")
    if [ -z "${someapes}" ]
    then
	echo "No ape files found in current directory"
    else
	losslessdir=$(basename "${PWD}")
	# vfatize directory name:	
	targetsubdir=$(vfatize "${losslessdir}")
	mkdir -p "${targetdir}/${targetsubdir}"
	# Don’t forget to vfatize lossless file names:
	for apefile in *.ape;
	do
	    vfatapefile0="${apefile%.*}.mp3"; vfatapefile=$(vfatize "${vfatapefile0}"); ffmpeg -i "$apefile" -ab 320k -map_metadata 0 -id3v2_version 3 "${targetdir}/${targetsubdir}/${vfatapefile}";
	done
    fi
    if [ -z "${someflacs}"  &&  -z "${someapes}" ]
    then
	highline2 "No known lossless files found in current directory" 
	return 1
    fi
    
    #    for losslessfile in *.lossless; do ffmpeg -i "$losslessfile" -ab 320k -map_metadata 0 -id3v2_version 3 "${targetdir}/${targetsubdir}/${losslessfile%.*}.mp3"; done
    # for pic in *.jpeg;
    for pic in *.{jpg,jpeg};
    do
    	y_or_n "Copy ${pic}"
    	if [ $? == 0 ]
    	then
    	    highline "Copying ${pic}"
    	    cp "${pic}" "${targetdir}/${targetsubdir}/${vfatmp3file}"
    	else
    	    highline "Not copying ${pic}"
    	fi	
    done
}

# Convert ogg to mp3 directly to target SD/stick
# Before calling cd to the HD dir containing ogg files, namely $oggdir
ogg2mp3 () # e.g. "/mnt/SDM32_05/collecs/Zique/Classic"
{
    if [ $# -ne 1 ]
    then
	echo "ogg2mp3 just takes a top directory target as argument.";
	return 1;
    fi
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	highline "Build mp3’s from all ogg’s in cwd make a subdir of target dir and put them in it."
	highline "General call: ogg2mp3 \"\$(basename \"\$PWD\")\""
	return
    fi
    someoggs=$(find . -maxdepth 1 -iname "*.ogg")
    if [ -z "${someoggs}" ]
    then
	echo "No ogg files found in current directory"
	return 1
    fi
    if [[ ! -e  "$1" || ! -d  "$1" || ! -w  "$1" ]]; then echo "$1" is not a valid target; return 1; fi
    targetdir="$1"
    oggdir=$(basename "${PWD}")
    # vfatize directory name:
    targetsubdir=$(vfatize "${oggdir}")
    mkdir -p "${targetdir}/${targetsubdir}"
    #    for oggfile in *.ogg; do ffmpeg -i "$oggfile" -ab 320k -map_metadata 0 -id3v2_version 3 "${targetdir}/${targetsubdir}/${oggfile%.*}.mp3"; done
    # Don’t forget to vfatize ogg file names:
    for oggfile in *.ogg;
    do vfatoggfile0="${oggfile%.*}.mp3"; vfatoggfile=$(vfatize "${vfatoggfile0}"); ffmpeg -i "$oggfile" -ab 320k -map_metadata 0 -id3v2_version 3 "${targetdir}/${targetsubdir}/${vfatoggfile}";
    done
    # for pic in *.jpeg;
    for pic in *.{jpg,jpeg};
    do
    	y_or_n "Copy ${pic}"
    	if [ $? == 0 ]
    	then
    	    highline "Copying ${pic}"
    	    cp "${pic}" "${targetdir}/${targetsubdir}/${vfatmp3file}"
    	else
    	    highline "Not copying ${pic}"
    	fi	
    done
}

# Only rsync mp3 to mp3 in target SD/stick
# Before calling cd to the HD dir already containing mp3 files, namely $flacdir
mp32mp3 ()
{
    if [ $# -ne 1 ]
    then
	echo "mp32mp3 just takes a top directory target as argument.";
	return 1;
    fi
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	highline "Only cp mp3 files when flac, wav etc. are present, ask for copying images"
	highline "General call: mp32mp3 \"\$(basename \"\$PWD\")\""
	return
    fi
    somemp3s=$(find . -maxdepth 1 -iname "*.mp3")
    if [ -z "${somemp3s}" ]
    then
	echo "No mp3 files found in current directory"
	return 1
    fi
    if [[ ! -e  "$1" || ! -d  "$1" || ! -w  "$1" ]]; then echo "$1" is not a valid target; return 1; fi

    targetdir="$1"
    mp3dir=$(basename "${PWD}")
    # vfatize directory name:
    targetsubdir=$(vfatize "${mp3dir}")
    mkdir -p "${targetdir}/${targetsubdir}"

    # Don’t forget to vfatize mp3 file names:
    for mp3file in *.mp3;
    do vfatmp3file0="${mp3file%.*}.mp3"; vfatmp3file=$(vfatize "${vfatmp3file0}"); cp "$mp3file" "${targetdir}/${targetsubdir}/${vfatmp3file}";
    done
    #    sync -nauPA -T /tmp -vvv --log-file=/tmp/rsync-log --exclude-from=/home/alex/etc/bu_excl_ape_flac --prune-empty-dirs "/mnt/ananas2/collecs/Zique/p2p/Haydn F.J. - The Sturm und Drang Symphonies - Pinnock 6 CD Set" /mnt/MEGAFEIS/
        # for pic in *.jpeg;
    for pic in *.{jpg,jpeg};
    do
    	y_or_n "Copy ${pic}"
    	if [ $? == 0 ]
    	then
    	    highline "Copying ${pic}"
    	    cp "${pic}" "${targetdir}/${targetsubdir}/${vfatmp3file}"
    	else
    	    highline "Not copying ${pic}"
    	fi	
    done
}


# Convert flac to mp3 Directly to target SD/stick
# First cd to the HD dir containing subdirs with flac files, namely
# flac2mp3_1stlevel () # ❤❤❤❤❤ When flac files are in first level subdirs.
# {
#     someflacs=$(find . -mindepth 2 -maxdepth 2 -iname "*.flac")
#     if [ -z "${someflacs}" ]
#     then
# 	echo "No flac files found in subdirs of cwd"
# 	return 1
#     fi
#     if [ $# -ne 1 ]
#     then
# 	echo "flac2mp3_1stlevel just takes a top directory target as argument.";
# 	return 1;
#     fi
#     if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
#     then
# 	highline "Build mp3’s from all flac’s in subdirs of cwd and put them in a corresponding subdir of target dir, given as sole argument"
# 	return
#     fi
#     if [[ ! -e  "$1" || ! -d  "$1" || ! -w  "$1" ]]; then echo "$1" is not a valid target; return 1; fi
#     toptgdir="$1"
#     middir=$(basename "${PWD}")
#     tgmiddir=$(vfatize "${middir}")
#     mkdir -p "${toptgdir}/${tgmiddir}"
#     for pic in *.{jpg,jpeg}; do cp ${pic} "$${toptgdir}/${tgmiddir}"; done
#     for dir in CD*; do cd "$dir"; flac2mp3 "${toptgdir}/${tgmiddir}"; cd ..; done
# }

flac2mp3_1stlevel () # ❤❤❤❤❤ When flac files are in first level subdirs.
{
for dir in CD*; do mkdir -p "${targetdir}/${targetsubdir}/$dir";  cd "$dir"; for flacfile in *.flac; do ffmpeg -i "$flacfile" -ab 320k -map_metadata 0 -id3v2_version 3 "${targetdir}/${targetsubdir}/$dir/${flacfile%.*}.mp3"; done; cd ..; done
}

# flac2mp3_1stlevel_test ()
# {
# flacdir=$(basename "${PWD}")
# targetsubdir=$(vfatize "${flacdir}")
# for dir in CD*; do mkdir "${targetdir}/${targetsubdir}/$dir"; done
# }

ape2flac () # ❤❤❤❤❤
{
    someapes=$(find . -maxdepth 1 -iname "*.ape")
    if [ -z "${someapes}" ]
    then
	echo "No ape files found in current directory"
	return 1
    fi
    if [ $# -ne 1 ]
    then
	echo "ape2flac just takes a top directory target as argument.";
	echo "Give .. to create flac’s in same directory.";
	return 1;
    fi
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	highline "Build flac’s from all ape’s in cwd and put them in a subdir of toptarget dir, given as sole argument"
	return
    fi
    if [[ ! -e  "$1" || ! -d  "$1" || ! -w  "$1" ]]; then echo "$1" is not a valid target; return 1; fi
    targetdir="$1"    
    apedir=$(basename "${PWD}")
    targetsubdir=$(vfatize "${apedir}")
    mkdir -p "${targetdir}/${targetsubdir}"
    for apefile in *.ape; do ffmpeg -i "$apefile"  -vn -sn -map_metadata 0 -id3v2_version 3 "${targetdir}/${targetsubdir}/${apefile%.*}.flac"; done
    for pic in *.{jpg,jpeg}; do cp ${pic} "${targetdir}/${targetsubdir}/${vfatmp3file}"; done
}


ape2flac_recur () #  in construction
{
    someapes=$(find . -mindepth 1 -iname "*.ape" -print -quit)
    if [ -z "${someapes}" ]
    then
	echo "No ape files found in any subdir of current directory"
	return 1
    fi
        if [ $# -ne 1 ]
    then
	echo "ape2flac just takes a top directory target as argument.";
	return 1;
    fi
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	highline "Build flac’s from all ape’s in cwd and put them in a subdir of toptarget dir, given as sole argument"
	return
    fi
    if [[ ! -e  "$1" || ! -d  "$1" || ! -w  "$1" ]]; then echo "$1" is not a valid target; return 1; fi

    targetdir="$1"        
    for md in *
    do
	if [[ -d  "$md" && -w "$md" ]];
	then
	    cd $md
	    ape2flac "$targetdir"
	    cd ..    
	fi
    done

    apedir=$(basename "${PWD}")
    targetsubdir=$(vfatize "${apedir}")
    mkdir -p "${targetdir}/${targetsubdir}"
    for apefile in *.ape; do ffmpeg -i "$apefile"  -vn -sn -map_metadata 0 -id3v2_version 3 "${targetdir}/${targetsubdir}/${apefile%.*}.flac"; done
    for pic in *.{jpg,jpeg}; do cp ${pic} "${targetdir}/${targetsubdir}/${vfatmp3file}"; done
}

mp3tomp3 () # e.g. "/mnt/SDM32_05/collecs/Zique/Classic"
{
    somemp3s=$(find . -maxdepth 1 -iname "*.mp3")
    if [ -z "${somemp3s}" ]
    then
	echo "No mp3 files found in current directory"
	return 1
    fi
    if [ $# -ne 1 ]
    then
	echo "mp3tomp3 just takes a top directory target as argument.";
	return 1;
    fi
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	highline "Put all mp3’s in cwd and put them in a subdir of target dir, given as sole argument"
	return
    fi
    if [[ ! -e  "$1" || ! -d  "$1" || ! -w  "$1" ]]; then echo "$1" is not a valid target; return 1; fi
    targetdir="$1"
    mp3dir=$(basename "${PWD}")
    # vfatize directory name:
    targetsubdir=$(vfatize "${mp3dir}")
    mkdir -p "${targetdir}/${targetsubdir}"
    #    for mp3file in *.mp3; do ffmpeg -i "$mp3file" -ab 320k -map_metadata 0 -id3v2_version 3 "${targetdir}/${targetsubdir}/${mp3file%.*}.mp3"; done
    # Don’t forget to vfatize mp3 file names:
    for mp3file in *.mp3 ; do vfatmp3file=$(vfatize "${mp3file}"); cp "${vfatmp3file}" "${targetdir}/${targetsubdir}/${vfatmp3file}"; done
    for pic in *.{jpg,jpeg}; do cp ${pic} "${targetdir}/${targetsubdir}/${vfatmp3file}"; done
}

splittracks ()# flacfile cuefile
{
    if [ $# -ne 2 ]	
    then
	echo "splittracks takes a big flac file and a cue file as arguments.";
	echo "splittracks \"${flacfile}\" \"${cuefile}\" "
	return 1;
    fi
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	highline "Split 1st arg flac file and correctly name the tracks according to 2nd arg cue file"
	return
    fi
    if [[ ! -e  "$1" || ! -f  "$1" ]]; then echo "$1" is not a valid writable flac; return 1; fi
    if [[ ! -e  "$2" || ! -f  "$2" ]]; then echo "$2" is not a valid cue file; return 1; fi
    # bnorig=$(basename "${flacfile}")
    # vfatname=$(vfatize "${bnorig}")
    flacfile="$1"
    cuefile="$2"
    #     -o 'flac flake - %f' (use alternate flac encoder) (man shnsplit)
    cuebreakpoints "$cuefile" | shnsplit -o flac "$flacfile"
    #    cuebreakpoints "$cuefile" | shnsplit "$flacfile"
    cat "${cuefile}" | sed -n '/[[:blank:]]TITLE/p' | sed 's/[[:blank:]]*TITLE[[:blank:]]//g' > /tmp/lulu
    declare -i counter
    counter=0
    while read line
    do
	echo line is $line
	cleanline=$(echo $line | sed 's#/#-#g' | sed 's/\"//g' | sed 's/\r//g' )
	echo cleanline is $cleanline
	counter=$((counter+1))
	str_counter=$(printf "%02g" ${counter})
	mv split-track${str_counter}.flac "${cleanline}.flac"
    done < /tmp/lulu
}

splittracksape ()# apefile cuefile
{
    if [ $# -ne 2 ]	
    then
	echo "splittracks takes a big ape file and a cue file as arguments.";
	echo "splittracks \"${apefile}\" \"${cuefile}\" "
	return 1;
    fi
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	highline "Split 1st arg ape file and correctly name the tracks according to 2nd arg cue file"
	highline2 "Currently DOES NOT WORK" ${BWhite} ${On_Red}
	return
    fi
    if [[ ! -e  "$1" || ! -f  "$1" ]]; then echo "$1" is not a valid writable ape; return 1; fi
    if [[ ! -e  "$2" || ! -f  "$2" ]]; then echo "$2" is not a valid cue file; return 1; fi
    # bnorig=$(basename "${apefile}")
    # vfatname=$(vfatize "${bnorig}")
    apefile="$1"
    cuefile="$2"
    cuebreakpoints "$cuefile" | shnsplit -o flac "$apefile"
    cat "${cuefile}" | sed -n '/[[:blank:]]TITLE/p' | sed 's/[[:blank:]]*TITLE[[:blank:]]//g' > /tmp/lulu
    declare -i counter
    counter=0
    while read line
    do
	echo line is $line
	cleanline=$(echo $line | sed 's#/#-#g' | sed 's/\"//g' | sed 's/\r//g' )
	echo cleanline is $cleanline
	counter=$((counter+1))
	str_counter=$(printf "%02g" ${counter})
	mv split-track${str_counter}.ape "${cleanline}.ape"
    done < /tmp/lulu
}

    # while read line
    # do
    # 	echo line is $line
    # done < /tmp/lulu

askdelpop ()
{
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	highline "Listen to and propose to delete music files givenin argument"
	highline "Ex: askdelpop \"*.mp3\""
	return
    fi
    for mf in $@;
    do
	echo Testing "${mf}"
	if [ -f "${mf}" ]
	then
	    nvlc "${mf}"
	    y_or_n "Keep it"
	    if [ $? == 0 ]
	    then
		echo "Keeping ${mf}" 
	    else
		echo "Deleting ${mf}"
		rm -f "${mf}"
	    fi
	fi
    done
}

# shopt -s expand_aliases
# source "/etc/bash_aliases"f

findplayer ()
{
    ext="$1"
    case "$ext" in avi | mov | webm | mp4 | mkv)
		       echo "Extension is $ext, running default video player $VIDEOPLAYER"
		       myplayer="$VIDEOPLAYER"
		       ;;
		    mp3 | flac | wav )
			echo "Extension is $ext, running default sound player $SOUNDPLAYER"
			myplayer="$SOUNDPLAYER" 
			;;
		    png | jpg | jpeg | svg | bmp )
			echo "Extension is $ext, running default image viewer  $IMAGEVIEWER"
			myplayer="$IMAGEVIEWER"
			;;
		    part )
			fnext="${fn##*.}";
			echo "Extension is $ext, partial download"
			myplayer="digup"
			;;
		    * )
			echo "Not a known media file."
			myplayer=""
			;;
    esac
}

askdelmedia ()
{
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	highline "Listen to and propose to delete music files givenin argument"
	highline "Ex: askdelpop \"*.mp3\""
	return
    fi
    for mf in "$@";
    do
	highline "Testing ${mf}";
	if [ -f "${mf}" ]
	then
	    mfb=$(basename "$mf");
	    ext="${mfb##*.}";
	    fn="${mfb%.*}"
	    findplayer "$ext"
	    if [ -z "$myplayer" ]
	    then
		echo "No player found for $mfb"
		# return 1		
	    elif [ "$myplayer" == "digup" ]
	    then
		echo "myplayer is digup"
		fnext="${fn##*.}";
		echo "fnext is $fnext"
		findplayer "$fnext"
	    fi
	    echo myplayer is "$myplayer"
	    firstmptoken=$(echo "$myplayer" | awk '{print $1}')
	    echo firstmptoken is "$firstmptoken"
	    #	    if [[ -n "$firstmptoken" && -f "$firstmptoken" && -x "$firstmptoken" ]]
	    if [ -n "$firstmptoken" ]
	    then $myplayer "$mf"
	    fi
	    y_or_n "Keep it"
	    if [ $? == 0 ]
	    then
		echo "Keeping ${mf}" 
	    else
		echo "Deleting ${mf}"
		rm -f "${mf}"
	    fi
	fi
    done
}

mv_and_link () # see also ~/bin/p2plinks
{    
    if [[ "$1" =~ "-help" || "$1" =~ "--help" || "$1" =~ "-h" ]]
    then
	highline "Put physical data in cwd to directory given as argument and slink to it from cwd"
	return
    fi
    torget="${1}"
    target="${1%%/}"
    echo torget is "$torget"
    echo target is "$target"
    if [ ! -d "$target" ]
    then
	highline "Argument is not a directory, exiting"
	return
    else
	for mf in *
	do
	    if [ -L "$mf" ]
	    then
		highline "Skipping soft link $mf"
	    elif [[ -d "$mf" || -f "$mf" ]]
	    then
		mv "$mf" "${target}"
		ln -s "${target}/$mf" .
	    else
		highline "Skipping $mfg"
	    fi
	done
    fi    
}

chroot_test ()
{
    beroot
    rooted=$?
    vecho beroot returned $rooted
    if [ "$rooted" != 0 ]
    then
	highline "Don’t know, be root to run this." "${BRed}"
	return 2
    fi
    if [ "$(stat -c %d:%i /)" != "$(stat -c %d:%i /proc/1/root/.)" ]; then
	highline "We are chrooted!"
	return 0
    else
	highline "Business as usual"
	return 1
    fi
    }

# $ countchar '"' <file.txt  #returns one count per line of file.txt
# $ countchar ')'           #will count parenthesis from stdin
# $ countchar '0123456789'  #will count numbers from stdin
function countchars()
{
    while IFS= read -r i; do printf "%s" "$i" | tr -dc "$1" | wc -m; done
}
