#!/bin/bash
#
CMD=`basename $0`

set -u
set -e


# checking parms
#
agent_parms=`kusa-conf ocsng.agent_parms`
fullhostname=false
revhostname=false

echo -- "$agent_parms" | grep -q -- "--fullhostname" && {
	fullhostname=true
	echo "  fullhostname = true" >&2
}
echo -- "$agent_parms" | grep -q -- "--revhostname" && {
	revhostname=true
	echo "  revhostname = true" >&2
}
[ "$fullhostname" != "true" -a "$revhostname" != "true" ] && {
	echo "neither --fullhostname or --revhostname defined in 'agent_parms'" >&2
	echo "nothing to do, closing" >&2
	exit 0
}

do_sql()
{
  #--delimiter=name
  #--execute=name
		#--table \
	mysql --batch --host=$db_host --database=$db_name \
		--user=$db_user --password=$db_password \
		--delimiter="|" \
		--execute="$*"
}

set_domains()
{
	local tag_lookup="/etc/ocsinventory-agent/tag2domain"
	local wg_lookup="/etc/ocsinventory-agent/workgroup2domain"

	while read id name workgroup tag
	do
		printf "%-12s %-20s %-12s   " $name $workgroup $tag >&2

		domain=
		echo "$workgroup" | fgrep -q '.' && {
			domain=$workgroup
			echo "wg=$workgroup OK" >&2
		}
		[ "$domain" == "" -a -r $tag_lookup ] && {
			domain=`grep "^$tag " $tag_lookup 2>/dev/null | cut -d' ' -f2`
			[ "$domain" != "" ] && echo "tag=$tag" >&2
		}
		[ "$domain" == "" -a -r $wg_lookup ] && {
			domain=`grep "^$workgroup " $wg_lookup 2>/dev/null | cut -d' ' -f2`
			[ "$domain" != "" ] && echo "wg=$workgroup" >&2
		}
		[ "$domain" == "" ] && {
			echo " no domain for tag/wg: $tag/$workgroup" >&2
			continue
		}
		echo "  update hardware set name = '$name.$domain' where id = '$id' ;"
	done
}




# checking credentials
#
db_host=`kusa-conf ocsng.db_host`
db_user=`kusa-conf ocsng.db_user`
db_password=`kusa-conf ocsng.db_password`
db_name=`kusa-conf ocsng.db_name`


rows=`do_sql "
	select
		id,name,workgroup,
		accountinfo.tag as tag
		from hardware
	   inner join accountinfo on (hardware.id = accountinfo.HARDWARE_ID)
	   where name not like '%.%'
	;" | sed -e '1d'
	`
[ "$rows" == "" ] && {
	echo " none found"
	exit 0
}

nrows=`echo "$rows" | wc -l`
echo "  found $nrows names without domain"
[ $nrows == 0 ] && exit 0

# setup update sql
#
sql=""
save_ifs="$IFS"
IFS="	"	# "tab" here

sql=`echo "$rows" | set_domains`
sql=`echo -e "$sql"`

echo -e "\nEXECUTING:\n"
echo "$sql"
do_sql "$sql"

exit 0
