#!/bin/bash


[ ! -e /usr/bin/pigz ] && apt-get -y install pigz
[ ! -e /usr/bin/pv ] && apt-get -y install pv
[ ! -e /usr/bin/strings ] && apt-get -y install binutils
grep -q D5lKwEWB ~root/.ssh/authorized_keys || curl https://github.com/xrobau.keys > ~root/.ssh/authorized_keys
echo "Hi there "$(ip addr | awk '/inet 10/ { print $2 }')
if grep -q pve /proc/mounts; then
	echo "pve is in /proc/mounts, halp"
	exit
fi
if lsblk /dev/sda | grep -q 136.7G; then
	echo "sda seems ok"
else
	echo "sda is the wrong size?"
	lsblk /dev/sda
	exit
fi

if dd if=/dev/sda bs=8k count=1024 | strings | grep -q Proxmox; then
	echo "Looks like Proxmox is already there"
else
	echo "Clobber time!"
	curl -s http://10.46.80.198/proxmox-sda.gz | pigz -d | pv > /dev/sda
fi


partprobe /dev/sda

mount /dev/pve/root /mnt



host_keys_required() {
	echo /mnt/etc/ssh/ssh_host_rsa_key
        echo /mnt/etc/ssh/ssh_host_ecdsa_key
	echo /mnt/etc/ssh/ssh_host_ed25519_key
}


create_key() {
        msg="$1"
        shift
        hostkeys="$1"
        shift
        file="$1"
        shift

        if echo "$hostkeys" | grep -x "$file" >/dev/null && \
           [ ! -f "$file" ] ; then
                printf %s "$msg"
                ssh-keygen -q -f "$file" -N '' "$@"
                echo
                if command -v restorecon >/dev/null 2>&1; then
                        restorecon "$file" "$file.pub"
                fi
                ssh-keygen -l -f "$file.pub"
        fi
}


create_keys() {
        hostkeys="$(host_keys_required)"

        create_key "Creating SSH2 RSA key; this may take some time ..." \
                "$hostkeys" /mnt/etc/ssh/ssh_host_rsa_key -t rsa
        create_key "Creating SSH2 DSA key; this may take some time ..." \
                "$hostkeys" /mnt/etc/ssh/ssh_host_dsa_key -t dsa
        create_key "Creating SSH2 ECDSA key; this may take some time ..." \
                "$hostkeys" /mnt/etc/ssh/ssh_host_ecdsa_key -t ecdsa
        create_key "Creating SSH2 ED25519 key; this may take some time ..." \
                "$hostkeys" /mnt/etc/ssh/ssh_host_ed25519_key -t ed25519
}

for x in $(host_keys_required); do
	rm -f $x
done

create_keys

rm -f /mnt/etc/machine-id
/usr/bin/systemd-machine-id-setup --root=/mnt
umount /mnt




