#!/bin/bash

# Common files/locations
ROOT_TARBALL="CMG-DCM-mk2x.tar.gz"
SUPPORT_TARBALL="support.tar.gz"
DESTINATION="/nand1"

# Check if the user has asked for DHCP or static
NET_TYPE="$1"
case "${NET_TYPE}" in
dhcp | DHCP)
	if [ $# -ne 1 ]
	then
		echo "Unexpected number of arguments. Expecting \`dhcp'."
		exit 1
	fi
	NET_TYPE="dhcp"
	NET_IP=""
	NET_MASK=""
	;;
static)
	if [ $# -ne 2 -a $# -ne 3 ]
	then
		echo "Unexpected number of arguments. Expecting \`static IP/BITS [GATEWAY]'."
		exit 1
	fi

	NET_IP="$2"
	NET_IP_BITS="$(echo ${NET_IP} | sed -e 's,^.*/,,')"
	NET_IP_OK="0"
	[ "${NET_IP_BITS}" -ge 1 ] && NET_IP_OK="1"
	[ "${NET_IP_BITS}" -gt 32 ] && NET_IP_OK="0"

	if [ "${NET_IP_OK}" -ne 1 ]
	then
		echo "Incorrect format for IP address. Use IP/BITS, e.g. 192.168.0.1/24"
		echo "for a /24 subnet (netmask 255.255.255.0). This is called CIDR format."
		exit 1
	fi

	NET_GATEWAY="$3"
	;;
*)
	echo "You need to specify \`dhcp' or \`static' for the IP address."
	exit 1
esac

# Check that files/locations exist
if [ ! -e "${ROOT_TARBALL}" ]
then
	echo "Cannot find the root tarball, \`${ROOT_TARBALL}'. Not continuing."
	exit 1
fi

if [ ! -e "${SUPPORT_TARBALL}" ]
then
	echo "Cannot find the support tarball, \`${SUPPORT_TARBALL}'. Not continuing."
	exit 1
fi

if [ ! -d "${DESTINATION}" ]
then
	echo "Cannot find unpack destination, \`${DESTINATION}'. Not continuing."
	exit 1
fi

# Clean ${DESTINATION} of files
(
	set -e
	echo "Making space for upgrade..."
	cd "${DESTINATION}"
	find . -type f | xargs -r rm
	sync
)
if [ $? -ne 0 ]
then
	echo "Failed to clean \`${DESTINATION}'. Not continuing."
	exit 1
fi

# Unpack tarballs
(
	set -e
	echo "Unpacking..."
	gunzip < "${ROOT_TARBALL}" | tar -C "${DESTINATION}" -xp
	gunzip < "${SUPPORT_TARBALL}" | tar -C "${DESTINATION}" -xp
	cp "${ROOT_TARBALL}" "${DESTINATION}/"
	sync
)
if [ $? -ne 0 ]
then
	echo "Failed to unpack to \`${DESTINATION}'. Not continuing."
	exit 1
fi

# Write network configuration
(
	set -e
	echo "Writing network configuration..."
	cat > "${DESTINATION}/support/new-ifcfg-eth0" <<EOF
# Auto-generated by upgrade-to-platinum.sh
NETCONFIG_VERSION="1"

# Interface settings
device="eth0"
desc="Primary wired network interface"
enable="True"
onboot="True"

# Device settings
media="Auto"
mtu=""

# DHCP settings
bootproto="${NET_TYPE}"
dhcpcd_args=""

# static settings, first address
default_address_ip="${NET_IP}"
default_address_broadcast=""
default_address_args=""
default_route_via="${NET_GATEWAY}"
default_route_args=""

# static settings, other addresses and routes
EOF
	cp -r "/etc/ssh" "${DESTINATION}/support/new-ssh"
	sync
)

# Rewrite /boot/params and reboot
echo "Rebooting to upgrader..."
echo "set linuxargs noinitrd root=/dev/mtdblock4 init=/support/stage2.sh console=ttyS0,115200" > /boot/params
sync
reboot -f
