#!/bin/bash
#
# Script for automated cloning and renaming of Fuss 9 client computers
# using mac-address as unique identifier.
# Donato Florio 11 April 2019
#
# Last modified 02 May 2019 --> added modification to support cloning on nvme* devices (HP G450)
# Last modified 07 May 2019 --> added various stuff for experimental autojoin
# 
# PRT 1 ---------------------------


# La funzione getNetStuff serve per recuperare il nome della NIC in uso sul sistema attuale. 
getNetStuff(){
    if [ $1 -eq 1 ];then
	ls /sys/class/net/ -1 | grep -v lo | grep -v wlan
    else
	cat /sys/class/net/$(getNetStuff 1)/address
    fi
}

getDisk(){
    diskCount="$(ls /sys/block -1 | grep -Ev '(loop|sr|dvd|cd)' | wc -l)"
    
    if [ $diskCount -gt 1 ];then
	echo "ATTENZIONE! Questo computer sembra provvisto di più di un disco!"
	echo ""
	echo "La procedura automatica non prevede l'installazione su sistemi"
	echo "multidisco. Contattare il tecnico informatico."
	echo ""
	echo "Per sicurezza il computer verrà spento tra 10 secondi."
	sleep 10
	shutdown -h now
    else
	diskVar="$(ls /sys/block -1 | grep -Ev '(loop|sr|dvd|cd)')"
    fi
    
    # SSD portatili HP g450 
    if [ $diskVar == "nvme0n1" ];then
	rootPartition="p$rootPartition"
    fi
    # FINE g450
}

rootPartition=2
getDisk
rootDisk="/dev/$diskVar"
mountPoint="/mnt"
computerList="/home/partimag/ListaPc.txt"
macAddress=$(getNetStuff 2)
imageName=$(cat $computerList | grep "$macAddress" | awk '{print $3}')

ocs-sr -b -g auto -e1 auto -e2 -r -j2 -scr -p true restoredisk $imageName $diskVar

# # PRT 2 ---------------------------
mount $rootDisk$rootPartition $mountPoint

currentName="$(cat $mountPoint/etc/hostname)"
newName="$(grep "$macAddress" $computerList | awk '{print $1}')"

echo "SETTING HOSTNAME" 

for i in hostname hosts mailname
	 
do
    if [ -e $mountPoint/etc/$i ]; then
	sed -ie "s/$currentName/$newName/g" $mountPoint/etc/$i
    else
	echo "The file $i is not present on this system"
    fi    
done



# ###  Here I insert the part for the joining preparation of the machine

# Veriy whether the machine has to be joined to the domain or not.
# If so the .ssh keys are needed and also a script ..... 

joinVar="$(cat $computerList | grep "$macAddress" | awk '{print $4}')" 

if [ "$joinVar" == "join" ];then
    rsync -a /home/partimag/.ssh/ /mnt/root/.ssh/
    cp /root/.ssh/known_hosts /mnt/root/.ssh/known_hosts
    cp /home/partimag/clientScripts/rc.local /mnt/etc/
    chmod 770 /mnt/etc/rc.local
    cp /home/partimag/clientScripts/clientScript /mnt/root/
    chmod 770 /mnt/root/clientScript
    touch /mnt/root/reboot
fi
# ### END of the preparation stuff


reboot


