#!/bin/sh

set -e

DEVICE="${1}"

# User is unprivileged
if [ "$(id -u)" -ne 0 ]
then
	echo "E: need root privileges"
	exit 1
fi

# User has not specified a device to install
if [ -z "${DEVICE}" ]
then
	echo "E: Usage: ${0} DEVICE"
	exit 1
fi

# User has specified a non-existing device
if [ ! -e "${DEVICE}" ]
then
	echo "E: cannot access \"${DEVICE}\": No such device"
	exit 1
fi

# User has specified an invalid device
if [ ! -b "${DEVICE}" ]
then
	echo "E: cannot access \"${DEVICE}\": No valid device"
	exit 1
fi

# Searching extlinux directory
echo -n "P: Searching for EXTLINUX directory..."

for LOCATION in /boot/extlinux /boot/boot/exlinux /extlinux
do
	if [ -e "${LOCATION}" ]
	then
		DIRECTORY="${LOCATION}"

		echo " found: ${DIRECTORY}"
		break
	fi
done

# Creating extlinux directory
if [ -z "${DIRECTORY}" ]
then
	echo " not found."

	DIRECTORY="/boot/extlinux"

	echo -n "P: Creating EXTLINUX directory..."
	mkdir -p "${DIRECTORY}"
	echo " done: ${DIRECTORY}"
fi

# Searching syslinux mbr
if [ ! -e /usr/lib/extlinux/mbr.bin ]
then
	echo "E: /usr/lib/extlinux/mbr.bin: No such file"
	exit 1
fi

# Writing syslinux mbr
echo "P: Installing mbr..."
dd if=/usr/lib/extlinux/mbr.bin of=${DEVICE} bs=466 count=1

# Writing extlinux loader
echo "P: Installing EXTLINUX..."
extlinux --install "${DIRECTORY}"
