#!/usr/bin/bash

if [ ! 0 -eq $(id -u) ]; then
	echo "Error: Sorry. You have to be root to run this script! Exit!" 1>&2;
	exit 1;
fi

echo "This Script generate 
- a new hostname
- a new mashine-id.
- a set of new ssh-hostkeys

Press [STRG] + [c] or let the hostname clear to break!
";

read -p "New hostname: " hostname;

if [ "" = "$hostname" ]; then
	echo "O.K. Exit!" 1>&2;
	exit 255;
fi

oldHostname=$(hostname); 

hostname "$hostname";
if [ 0 -ne $? ]; then
	exit 2;
fi

echo -n $hostname > /etc/hostname
sed -i".backup" -e "s/$oldHostname/$hostname/g" /etc/hosts
echo "New file /etc/hosts:";
cat /etc/hosts;

rm -f /etc/machine-id
if [ -x /usr/bin/systemd-machine-id-setup ]; then
	/usr/bin/systemd-machine-id-setup;
elif  [ -x /usr/bin/dbus-uuidgen ]; then
	/usr/bin/dbus-uuidgen --ensure=/etc/machine-id;
else
	dd if=/dev/random bs=16 count=1 2>/dev/null | hexdump |  head -n1 | cut -d " " -f 2,3,4,5,6,7,8,9 --output-delimiter="" > /etc/machine-id;
	echo "" >> /etc/machine-id;
fi
echo -n "New machine-id: "; cat /etc/machine-id;

if [ -w "/var/lib/dbus/machine-id" ]; then
	cat "/etc/machine-id" > "/var/lib/dbus/machine-id" 
	echo "... copied to /var/lib/dbus/machine-id":
fi

cd /etc/ssh;
keyFiles=$(ls ssh_host_*_key);
for keyFile in $keyFiles; do
	method=$(echo -n $keyFile | cut -d "_" -f3);
	rm $keyFile;
	ssh-keygen -q -N "" -t $method -f $keyFile;
done
cd $OLDPWD;
	
echo "You shold control the output and reboot the machine now."
read -p "reboot now? y/[n]" a;
a=$(echo -n "$a" | tr "YJj" "y");
if [ "y" = $a ]; then
	reboot;
fi

