#!/bin/bash
. /usr/share/ltsp/plugins/functions 

set -e

usage() {
cat <<EOF
$0 [OPTION]
  -b, --basedir     Base of ltsp chroot.  Default is /opt/ltsp/$ARCH if unspecified.
  -h, --help        This message.
EOF
}

#
# Handle args
#

ARGS=$(getopt -o b:h --long base:,help \
       -n $0 -- "$@")

[ $? != 0 ] && exit 1

eval set -- "${ARGS}"

while true ; do
    case "$1" in
        -b|--base)        BASE=$2 ; shift 2 ;;
        -h|--help)        usage ; exit 0 ;;
        --) shift ; break ;;
        *) echo "Internal error!" ; exit 1 ;;
    esac
done

BASE=${BASE:-"/opt/ltsp"}

# TODO: Add optional parameters to allow use of non-latest kernel

# Check and set ARCH if necessary
if [ -z $ARCH ]; then
    UNAMEM="$(uname -m)"
    case $UNAMEM in
    i386|i586|i686|x86_64)
        ARCH=i386
    ;;
    ppc|ppc64)
        ARCH=ppc
    ;;
    *)
        ARCH="$UNAMEM" 
    ;;
    esac
    echo "ARCH not defined, assuming $ARCH."
fi
# Set ROOT
ROOT="$BASE/$ARCH"

detect_latest_kernel
[[ -z $kernelversion ]] && exit 127

# Find and symlink kernel and initrd
cd $ROOT/boot
kernel=`find . -type f -name "*$kernelversion*" | grep -E '^./(vmlinuz|kernel)' | sort | head -1`
initrd=`find . -type f -name "initr*$kernelversion*" ! -name "*~" | sort | head -1`

function do_symlink()
{
	dest="$1"
	name="$2"
	if [ -z "$dest" -o -z "$name" ]; then
		echo "do_symlink: 2 arguments are expected" >&2
		return
	fi

	chmod 0644 "$dest"
	if [ "`readlink "$name" || /bin/true`" != "$dest" ]; then
		mv "$name" "$name-prev" 2>/dev/null || /bin/true
	fi
	ln -sf "$dest" "$name"
}

do_symlink "$kernel" vmlinuz.ltsp
do_symlink "$initrd" initrd.ltsp
cd - > /dev/null

echo "${BASE##*/} ${ARCH}"
echo "	$kernel"
echo "	$initrd"
