#!/bin/sh

## Copyright (C) 2006-2013 Daniel Baumann <daniel.baumann@progress-technologies.net>
##
## This program comes with ABSOLUTELY NO WARRANTY; for details see COPYING.
## This is free software, and you are welcome to redistribute it
## under certain conditions; see COPYING for details.


set -e

_DEVICE="${1}"

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

_DIRECTORY="/boot/extlinux"

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

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

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

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

# Creating extlinux directory
if [ ! -e "${_DIRECTORY}" ]
then
	echo " not found."

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

# FIXME: hackish check for GPT but better than nothing
if dd if=${_DEVICE} count=440 2>&1 | strings | grep -qs '^EFI PART'
then
	_MBR="gptmbr"
else
	_MBR="mbr"
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

# Saving old MBR
echo -n "P: Saving old ${_MBR}..."
dd if="${_DEVICE}" of=/boot/${_MBR}-$(basename "${_DEVICE}").old bs=440 count=1 2> /dev/null
echo " done: /boot/${_MBR}-$(basename "${_DEVICE}").old"

# Writing syslinux MBR
echo -n "P: Writing new ${_MBR}..."
dd if=/usr/lib/extlinux/${_MBR}.bin of="${_DEVICE}" bs=440 count=1 2> /dev/null
echo " done: ${_DEVICE}"

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