#! /bin/sh

# Install SRM on your drive.
#   Copyright (C) 1999, 2000 Free Software Foundation, Inc.
#
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

# Initialize some variables.
prefix=/usr
exec_prefix=${prefix}
sbindir=${exec_prefix}/sbin
datadir=${prefix}/share
PACKAGE=srm
VERSION=0.01
host_cpu=i386
host_os=linux-gnu
host_vendor=pc
pkgdatadir=${datadir}/${PACKAGE}/${host_cpu}-${host_vendor}

srm_shell=${sbindir}/srm
log_file=/tmp/srm-install.log.$$
rootdir=
srm_prefix=/boot/srm

install_device=
force_lba=
recheck=no
debug=no
justcopy=no

# Usage: usage
# Print the usage.
usage () {
    cat <<EOF
Usage: srm-install [OPTION] install_device
Install SRM on your drive.

  -h, --help              print this message and exit
  -v, --version           print the version information and exit
  --root-directory=DIR    install SRM images under the directory DIR
                          instead of the root directory
  --srm-shell=FILE       use FILE as the srm shell
  --force-lba             force SRM to use LBA mode even for a buggy
                          BIOS
  --recheck               probe a device map even if it already exists

INSTALL_DEVICE can be a SRM device name or a system device filename.

Report bugs to <freevms@free.fr>.
EOF
}

# Usage: convert os_device
# Convert an OS device to the corresponding SRM drive.
# This part is OS-specific.
convert () {
    # First, check if the device file exists.
    if test -e "$1"; then
	:
    else
	echo "$1: Not found or not a block device." 1>&2
	exit 1
    fi

    # Break the device name into the disk part and the partition part.
    case "$host_os" in
    linux*)
	tmp_disk=`echo "$1" | sed -e 's%\([sh]d[a-z]\)[0-9]*$%\1%' \
				  -e 's%\(fd[0-9]*\)$%\1%' \
				  -e 's%/part[0-9]*$%/disc%'`
	tmp_part=`echo "$1" | sed -e 's%.*/[sh]d[a-z]\([0-9]*\)$%\1%' \
				  -e 's%.*/fd[0-9]*$%%' \
				  -e 's%.*/\(disc\|part\([0-9]*\)\)$%\2%'`
	;;
    gnu*)
	tmp_disk=`echo "$1" | sed 's%\([sh]d[0-9]*\).*%\1%'`
	tmp_part=`echo "$1" | sed "s%$tmp_disk%%"` ;;
    freebsd*)
	tmp_disk=`echo "$1" | sed 's%r\{0,1\}\([saw]d[0-9]*\).*$%r\1%' \
			    | sed 's%r\{0,1\}\(da[0-9]*\).*$%r\1%'`
	tmp_part=`echo "$1" \
	    | sed "s%.*/r\{0,1\}[saw]d[0-9]\(s[0-9]*[a-h]\)%\1%" \
       	    | sed "s%.*/r\{0,1\}da[0-9]\(s[0-9]*[a-h]\)%\1%"`
	;;
    *)
	echo "srm-install does not support your OS yet." 1>&2
	exit 1 ;;
    esac

    # Get the drive name.
    tmp_drive=`grep -v '^#' $device_map | grep "$tmp_disk *$" \
	| sed 's%.*\(([hf]d[0-9][a-g0-9,]*)\).*%\1%'`

    # If not found, print an error message and exit.
    if test "x$tmp_drive" = x; then
	echo "$1 does not have any corresponding BIOS drive." 1>&2
	exit 1
    fi

    if test "x$tmp_part" != x; then
	# If a partition is specified, we need to translate it into the
	# SRM's syntax.
	case "$host_os" in
	linux*)
	    echo "$tmp_drive" | sed "s%)$%,`expr $tmp_part - 1`)%" ;;
	gnu*)
	    if echo $tmp_part | grep "^s" >/dev/null; then
		tmp_pc_slice=`echo $tmp_part \
		    | sed "s%s\([0-9]*\)[a-g]*$%\1%"`
		tmp_drive=`echo "$tmp_drive" \
		    | sed "s%)%,\`expr "$tmp_pc_slice" - 1\`)%"`
	    fi
	    if echo $tmp_part | grep "[a-g]$" >/dev/null; then
		tmp_bsd_partition=`echo "$tmp_part" \
		    | sed "s%[^a-g]*\([a-g]\)$%\1%"`
		tmp_drive=`echo "$tmp_drive" \
		    | sed "s%)%,$tmp_bsd_partition)%"`
	    fi
	    echo "$tmp_drive" ;;
	freebsd*)
	    if echo $tmp_part | grep "^s" >/dev/null; then
		tmp_pc_slice=`echo $tmp_part \
		    | sed "s%s\([0-9]*\)[a-h]*$%\1%"`
		tmp_drive=`echo "$tmp_drive" \
		    | sed "s%)%,\`expr "$tmp_pc_slice" - 1\`)%"`
	    fi
	    if echo $tmp_part | grep "[a-h]$" >/dev/null; then
		tmp_bsd_partition=`echo "$tmp_part" \
		    | sed "s%s\{0,1\}[0-9]*\([a-h]\)$%\1%"`
		tmp_drive=`echo "$tmp_drive" \
		    | sed "s%)%,$tmp_bsd_partition)%"`
	    fi
	    echo "$tmp_drive" ;;
	esac
    else
	# If no partition is specified, just print the drive name.
	echo "$tmp_drive"
    fi
}

copy_images() {
	# Copy the GRUB images to the GRUB directory.
	for file in ${srmdir}/stage1 ${srmdir}/stage2 ${srmdir}/*stage1_5; do
	rm -f $file || exit 1
	done
	for file in \
	${pkgdatadir}/stage1 ${pkgdatadir}/stage2 ${pkgdatadir}/*stage1_5; do
	cp -f $file ${srmdir} || exit 1
	done
}

# Check the arguments.
for option in "$@"; do
    case "$option" in
    -h | --help)
	usage
	exit 0 ;;
    -v | --version)
	echo "srm-install (GNU SRM ${VERSION})"
	exit 0 ;;
    --root-directory=*)
	rootdir=`echo "$option" | sed 's/--root-directory=//'` ;;
    --srm-shell=*)
	srm_shell=`echo "$option" | sed 's/--srm-shell=//'` ;;
    --force-lba)
	force_lba="--force-lba" ;;
    --recheck)
	recheck=yes ;;
	--just-copy)
	justcopy=yes ;;
    # This is an undocumented feature...
    --debug)
	debug=yes ;;
    *)
	if test "x$install_device" != x; then
	    echo "More than one install_devices?" 1>&2
	    usage
	    exit 1
	fi
	install_device="${option}" ;;
    esac
done

# If the debugging feature is enabled, print commands.
if test $debug = yes; then
    set -x
fi

# Initialize these directories here, since ROOTDIR was initialized.
bootdir=${rootdir}/boot
srmdir=${bootdir}/srm
device_map=${srmdir}/device.map

# if they just want the images copied, copy the images and then exit
if test $justcopy = yes; then
	copy_images
	exit 0
fi

if test "x$install_device" = x; then
	echo "install_device not specified." 1>&2
	usage
	exit 1
fi


# Check if SRM is installed
if test -f "$srm_shell"; then
    :
else
    echo "${srm_shell}: Not found." 1>&2
    exit 1
fi

if test -f "$pkgdatadir/stage1"; then
    :
else
    echo "${pkgdatadir}/stage1: Not found." 1>&2
    exit 1
fi

if test -f "$pkgdatadir/stage2"; then
    :
else
    echo "${pkgdatadir}/stage2: Not found." 1>&2
    exit 1
fi

# Don't check for *stage1_5, because it is not fatal even if any
# Stage 1.5 does not exist.

# Create the SRM directory if it is not present.
test -d "$bootdir" || mkdir "$bootdir" || exit 1
test -d "$srmdir" || mkdir "$srmdir" || exit 1

# Copy the SRM images to the SRM directory.
copy_images

# If --recheck is specified, remove the device map, if present.
if test $recheck = yes; then
    rm -f $device_map
fi

# Create the device map file if it is not present.
if test -f "$device_map"; then
    :
else
    # Create a safe temporary file.
	test -x /bin/mktemp && log_file=`/bin/mktemp /tmp/srm-install.log.XXXXXX`

    $srm_shell --batch --device-map=$device_map <<EOF >$log_file
quit
EOF
    if grep "Error [0-9]*: " $log_file >/dev/null; then
	cat $log_file 1>&2
	exit 1
    fi

    rm -f $log_file
fi

# Check for INSTALL_DEVICE.
case "$install_device" in
/dev/*)
    install_drive=`convert "$install_device"`
    # I don't know why, but some shells wouldn't die if exit is
    # called in a function.
    if test "x$install_drive" = x; then
	exit 1
    fi ;;
\([hf]d[0-9]*\))
    install_drive="$install_device" ;;
*)
    echo "Format of install_device not recognized." 1>&2
    usage
    exit 1 ;;
esac

# Get the root drive.
# For now, this uses the program `df' to get the device name, but is
# this really portable?
root_device=`df ${rootdir}/ | grep /dev/ \
    | sed 's%.*\(/dev/[^ 	]*\).*%\1%'`
bootdir_device=`df ${bootdir} | grep /dev/ \
    | sed 's%.*\(/dev/[^ 	]*\).*%\1%'`

# Check if the boot directory is in the same device as the root directory.
if test "x$root_device" != "x$bootdir_device"; then
    # Perhaps the user has a separate boot partition.
    root_device=$bootdir_device
    srm_prefix="/srm"
fi

# Convert the root device to a SRM drive.
root_drive=`convert "$root_device"`
if test "x$root_drive" = x; then
    exit 1
fi

# Check if the root directory exists in the same device as the srm
# directory.
srmdir_device=`df ${srmdir} | grep /dev/ \
    | sed 's%.*\(/dev/[^ 	]*\).*%\1%'`
if test "x$srmdir_device" != "x$root_device"; then
    # For now, cannot deal with this situation.
    cat <<EOF 1>&2
You must set the root directory by the option --root-directory, because
$srmdir does not exist in the root device $root_device.
EOF
    exit 1
fi

# Create a safe temporary file.
test -x /bin/mktemp && log_file=`/bin/mktemp /tmp/srm-install.log.XXXXXX`

# Now perform the installation.
$srm_shell --batch --device-map=$device_map <<EOF >$log_file
set root $root_drive
setup $force_lba --stage2=$srmdir/stage2 --prefix=$srm_prefix $install_drive
quit
EOF

if grep "Error [0-9]*: " $log_file >/dev/null || test $debug = yes; then
    cat $log_file 1>&2
    exit 1
fi

rm -f $log_file

# Prompt the user to check if the device map is correct.
echo "Installation finished. No error reported."
echo "This is the contents of the device map $device_map."
echo "Check if this is correct or not. If any of the lines is incorrect,"
echo "fix it and re-run the script \`srm-install'."
echo

cat $device_map

# Bye.
exit 0
