#!/bin/sh -e
#
# The script to copy ALT Linux system from LiveCD to harddisk
#
# Copyright (C) 2010-2011 Eugene Prokopiev  <enp@altlinux.org>
# Copyright (C) 2011      Michael Pozhidaev <msp@altlinux.org>

THIS="${0##*/}"

if [ -z "$2" ]; then
    cat <<EOF

The script to copy ALT Linux system from LiveCD to harddisk

Usage:
    $THIS [--no-lilo] BOOT_DEVICE ROOT_DEVICE

EOF
    exit 1
fi

NO_LILO=no

if [ "$1" == '--no-lilo' ]; then
    NO_LILO=yes
    shift
fi

BOOT_DEVICE="$1"
ROOT_DEVICE="$2"

if ! [ -e "$ROOT_DEVICE" ]; then 
    echo "$THIS:$ROOT_DEVICE is not a valid device for root file system" >&2
    exit 1
fi

if ! [ -e "$BOOT_DEVICE" ]; then 
    echo "$THIS:$BOOT_DEVICE is not a valid device for boot loader installation" >&2
    exit 1
fi

echo "Creating ext4 file system on $ROOT_DEVICE"
/sbin/mkfs.ext4 "$ROOT_DEVICE" &> /dev/null

TMPDIR="$(/bin/mktemp -d)"
/bin/mount "$ROOT_DEVICE" "$TMPDIR"

echo "Filling root partition with basic content"
live-install-fill-root "$TMPDIR"

echo "Making root partition clean up"
live-install-post "$TMPDIR"

echo "Generating lilo.conf"
live-install-gen-lilo-conf "$BOOT_DEVICE" "$ROOT_DEVICE" > "$TMPDIR/etc/lilo.conf"

echo "Generating fstab"
live-install-gen-fstab "$ROOT_DEVICE" > "$TMPDIR/etc/fstab"

echo "Installing the linux kernel"
live-install-kernel "$TMPDIR" > /dev/null

if [ "$NO_LILO" != 'yes' ]; then
    echo "Installing lilo"
    live-install-lilo "$TMPDIR" > /dev/null
fi

echo "Executing local installation scripts"
live-install-local-scripts "$TMPDIR"

#LIVEPKGS=$(rpm -qa | grep ^live)
#/sbin/chroot . rpm -e $LIVEPKGS
#/sbin/chroot . /sbin/chkconfig sshd on
#/sbin/chroot . /sbin/chkconfig acpid on

cd /
/bin/umount $ROOT_DEVICE
/bin/rmdir "$TMPDIR"

echo 'Everything is done successfully!'
