#!/bin/bash
#
# This is an example script that install and configure grub after installation.
# To use it put it in your CUSTOMIZE_DIR and make it executable.

set -e

. common.sh

CLEANUP=( )

trap cleanup EXIT

if [ -z "$TARGET" -o ! -d "$TARGET" ]; then
	echo "Missing target directory"
	exit 1
fi

# install grub
export LANG=C
if [ "$PROXY" ]; then
	export http_proxy="$PROXY"
	export https_proxy="$PROXY"
fi

if [ -n "$ARCH" ]; then
	_SRCS="-n th-$ARCH"
else
	_SRCS=
	for s in ${REPOS:-th}; do
		_SRCS="$_SRCS -n $s"
	done
fi
poldek $_SRCS -iGv --noask --root=$TARGET grub2 grub2-platform-pc

# fool grub autodetecion fails on LVM
LOOPDEV=$(losetup --show -f $BLOCKDEV)
CLEANUP+=("losetup -d $LOOPDEV")

mount --bind /dev $TARGET/dev
CLEANUP+=("umount $TARGET/dev")

mount --bind /proc $TARGET/proc
CLEANUP+=("umount $TARGET/proc")

mount --bind /sys $TARGET/sys
CLEANUP+=("umount $TARGET/sys")

# execute update-grub
chroot "$TARGET" update-grub

# install grub to the block device
chroot "$TARGET" grub-install $LOOPDEV

# execute cleanups
cleanup
trap - EXIT

exit 0
