#!/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 BOOT_DEVICE ROOT_DEVICE

EOF
    exit 1
fi

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

/sbin/mkfs.ext4 "$ROOT_DEVICE" > /dev/null
TMPDIR="$(/bin/mktemp -d)"
/bin/mount "$ROOT_DEVICE" "$TMPDIR"
cd "$TMPDIR"
/bin/cp -a /bin /boot /etc /lib* /root /sbin /usr /var /home .
/bin/mkdir dev media mnt proc srv sys tmp selinux cgroup
/bin/cat /usr/share/live-install/dev.cpio.bz2 | bunzip | cpio -i > /dev/null 2>&1
/bin/rm -f ./etc/rc.d/rc.local
/bin/rm -f ./etc/issue
/bin/rm -f ./etc/mtab
/bin/touch ./etc/mtab
/usr/bin/subst "/^REMOUNT_ROOTFS_RW_COMMAND/d" ./etc/sysconfig/init

/bin/mount -o bind /dev ./dev
/bin/mount -o bind /sys ./sys
/bin/mount -o bind /proc ./proc

if grep -q "$(basename $BOOT_DEVICE) : active raid1" /proc/mdstat ; then
    MD_OPTION_LILO="raid-extra-boot=\"mbr-only\""
fi

/bin/cat >> ./etc/lilo.conf << EOF
map="/boot/map"
lba32
compact
boot="$BOOT_DEVICE"
default="linux"
$MD_OPTION_LILO

image="/boot/vmlinuz"
	label="linux"
	initrd="/boot/initrd.img"
	root="$ROOT_DEVICE"
	read-only
EOF

head -n 3 /etc/fstab > ./etc/fstab

for part in `awk '(NR>2){print $4}' /proc/partitions`; do
    if [ "`fstyp /dev/$part`" = "swap" ]; then
        echo "/dev/$part	swap	swap	defaults	0 0" >> ./etc/fstab
    fi
done

/bin/cat >> ./etc/fstab << EOF
$ROOT_DEVICE	/		ext4	relatime	1 1
EOF

for script in `ls /usr/share/live-install/scripts.d/`
do
    . /usr/share/live-install/scripts.d/$script
done

LIVEPKGS=$(rpm -qa | grep ^live)

/sbin/chroot . /sbin/installkernel --nolaunch "$(uname -r)"
/sbin/chroot . /sbin/lilo
/sbin/chroot . rpm -e $LIVEPKGS
/sbin/chroot . /sbin/chkconfig sshd on
/sbin/chroot . /sbin/chkconfig acpid on

/bin/umount proc
/bin/umount sys
/bin/umount dev

cd /
/bin/umount $ROOT_DEVICE
#rm -rf "$TMPDIR"

echo 'Everything is done successfully!'
