#!/bin/bash
  
sleep 5
pass=$(cat /var/lib/dhcp/dhclient* | awk '/password/ {print $3; exit}' | awk -F\" '{print $2}')
nfs_server=$(cat /var/lib/dhcp/dhclient* | awk '/dhcp-server-identifier/ {print $3; exit}' | tr -d \;)
public_ip=$(cat /var/lib/dhcp/dhclient* | awk '/public-ip/ {print $3; exit}' | awk -F\" '{print $2}')
public_gateway=$(cat /var/lib/dhcp/dhclient* | awk '/public-gateway/ {print $3; exit}' | tr -d \;)
first_if=$(ip link show | tr -d ' ' | awk -F: '/[<>]/ {if ($2!="lo") print $2'} | head -1)
second_if=$(ip link show | tr -d ' ' | awk -F: '/[<>]/ {if ($2!="lo") print $2'} | head -2 | tail -1)

echo "root:$pass" | chpasswd
echo -e "$nfs_server\tnfs-server" >> /etc/hosts
#curl -s "http://$nfs_server:8300/disable-rescue-boot"
mount -a
if [ -n "$public_ip" ] && [ -n "$public_gateway" ]
then
    ip addr add $public_ip dev $first_if
    cat <<EOF> /etc/network/interfaces
auto lo
iface lo inet loopback

allow-hotplug $first_if
iface $first_if inet dhcp
auto $first_if 
iface $first_if inet static
        address $public_ip
        netmask $(ipcalc $public_ip | awk '/Netmask:/ {print $2}')
        gateway $public_gateway

allow-hotplug $second_if
iface $second_if inet dhcp
EOF
        systemctl restart networking
        ip route delete default
        ip route add default via $public_gateway
fi

installcommand="$(cat /proc/cmdline | grep -oP 'installcommand=\"[^"]*' | awk -F\" '{print $2}')"
if [ -n "$installcommand" ]
then
	curl -s "http://$nfs_server:8300/disable-rescue-boot"
	eval $installcommand
	/usr/sbin/reboot        
fi

