#!/bin/bash
# Copyright (c) 2019 Marco Marinello <mmarinello@fuss.bz.it>

case $1 in
	rootpw)
		read -s -p "Clients password: " pw1
		echo
		read -s -p "Confirm clients password: " pw2
		echo

		if ! [ "$pw1" = "$pw2" ] ; then
			echo "Password mismatch! Please retry"
		else
			perl -e "print crypt(\"$pw1\", \"salt\")" > $(cat /etc/fuss-fucc/sftpdir)/clientScripts/new_root_pw
		fi

		unset pw1
		unset pw2
		
		;;
	octolist)
		IMAGE="$2"
		JOIN="join"
		DB="/var/lib/octofuss/octofuss.db"
		OUTFILE="$(cat /etc/fuss-fucc/sftpdir)/computerList.txt.octo-new"

		rm -f ${OUTFILE}
		touch ${OUTFILE}

		PCS=$(sqlite3 $DB <<EOF
select distinct hostname from client_component;
.quit
EOF
		)

		for fqdn in $PCS; do
		        client=$(echo $fqdn | cut -d '.' -f 1)
		        # Check if the host has already been mapped
		        if ! grep $client ${OUTFILE} 2>&1 > /dev/null; then
		                # Find that MAC
		                MAC=$(sqlite3 $DB <<EOF
select value from client_component where hostname = "$fqdn" and component like "mac%";
.quit
EOF
		)
		                MAC=$(echo $MAC|cut -d ' ' -f 1)
		                if [ -z "$MAC" ] ; then
		                        echo "No mac for ${fqdn}"
		                else
					if ! grep $MAC ${OUTFILE} 2>&1 > /dev/null ; then
						THIS="$IMAGE"
			                        echo $client $MAC $THIS $JOIN $(grep $client /etc/clusters | head -1 | cut -d ' ' -f 1) >> ${OUTFILE}
					else
						echo "$MAC has more than one fqdn (${fqdn})"
					fi
		                fi
		        fi
		done

		;;
	*)
		echo "Usage: $0 [SUBCOMMAND]"
		echo
		echo -e "\trootpw\t\tGenerate and save the root\n\t\t\tpassword for the installed clients"
		echo -e "\toctolist [image]\tGenerate the computerList.txt from\n\t\t\tthe OctoFuss database"
		
		;;
esac
