#! /usr/bin/bash
#
# Nodeattr is not designed for hostname.domain.tld, just hostname
# it work to Debian 9 by accident.
# if debian > 9, original genders is copyed on /tmp, but . are replaced by ^
# binary of nodeattr is renamed /usr/bin/nodeattr.bin
# this script replace requested fqdn host.domain.tld by host^domain^tld (like content of copy of genders in /tmp)
# nodeattr.bin see ^ as normal char like a simple nodename then it parse stdout of nodeattr.bin by a sed to replace ^ by .
#
MinWork=10
# ---------------------------------------------------------------------------------------------------------------
# Calculate temp file
RNDSeq=$(echo $RANDOM$RANDOM$RANDOM | cut -b1-6)
TMPFile=/tmp/Alt-genders.$$-${RNDSeq}
AllParameters="$@"
OldOption="@@@"
NewParam=""
# Fixe gender file
PossibleGenders=$2
GenderFile=/etc/genders
# ---------------
[ "$(echo ${AllParameters} | grep "\-f" | wc -l)" = "1" ] && GenderFile=$2
# 
# this  FN generate valid cmd line for nodeattr.bin
# ex:         -f /etc/gender.sample -n jackyix01.idiap.ch -l si_target
# become      -f /tmp/ALT-Genders.$$-nnnnnn -n jackyix01^idiap^ch -l si_target
#   -f gender file is changed to temp gender file 
#   if -n hostname . replaced by ^
# ---------------------------------------------------------------------------------------------------------------

_RemovePointOnFQDNParam()
{
echo -n "-f ${TMPFile}"
for Option in ${AllParameters}
   do

   if [ "o${OldOption}" = "o-l" ]
      then
      echo -n " ${Option}" | sed s/'\.'/'^'/g
   elif [ "o${OldOption}" = "o-f" ]
        then
        #PATCH dont echo option followed by -f (already set before)
        echo -n ""
   elif [ "o${Option}" = "o-f" ]
        then
        #PATCH dont echo  -f option (already set before)
        echo -n ""
   else
      echo -n " ${Option}"
   fi
   OldOption=${Option}
done
}
# ---------------------------------------------------------------------------------------------------------------
NewParam=""
NewParam=$(_RemovePointOnFQDNParam $2)
# ----------------------------------------------------------------------
if [ $(cat /etc/debian_version  | awk -F "." ' { print $1 } ') -lt ${MinWork} ]
   then
   /usr/bin/nodeattr $*
   exit
else
   # Dirty hack
   #echo  ":${AllParameters}" >> /tmp/nodeattr.txt
   cat ${GenderFile} | sed s/'\.'/'^'/g > ${TMPFile} 2> /dev/null
   # Remove -f genderfile on options
   /usr/bin/nodeattr.bin ${NewParam} | sed s/'\^'/'.'/g
   [ -f ${TMPFile} ] && rm -f ${TMPFile} > /dev/null 2>&1
fi
