#!/bin/sh -e
# The script to clone LiveCD system to harddisk
# Eugene Prokopiev <enp@altlinux.org>
# Michael Pozhidaev <msp@altlinux.org>
# Date: 2011-01-28;

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

if [ -z "$2" ]; then
    cat <<EOF
The script to copy ALT Linux Homeros system from LiveCD to harddisk

Usage:
  $THIS BOOT_DEVICE ROOT_DEVICE
EOF
    exit 1
fi

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

/sbin/mkfs.ext3 "$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 .
/bin/mkdir dev home media mnt proc srv sys tmp
/bin/cat /usr/share/homeros-install/dev.cpio.bz2 | bunzip | cpio -i > /dev/null 2>&1
#/bin/mv -f ./etc/issue.save ./etc/issue
/bin/rm -f ./etc/rc.d/rc.local
/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

/sbin/mkinitrd -f --with=ext3.ko ./boot/initrd-`uname -r`.img `uname -r`

cd ./boot
if [ "$(ls vmlinuz* | wc -l)" == 1 ]; then
vmlinuz="$(ls vmlinuz*)"
echo "Creating symlink to $vmlinuz"
ln -s "$vmlinuz" vmlinuz
fi

if [ "$(ls initrd-* | wc -l)" == 1 ]; then
INITRD="$(ls initrd-*)"
echo "Creating symlink to $INITRD"
ln -s "$INITRD" initrd.img
fi

cd ..

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

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

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

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

/sbin/chroot . lilo
/sbin/chroot . rpm -e remount_rw
/sbin/chroot . /sbin/chkconfig sshd on
/sbin/chroot . /sbin/chkconfig acpid on
/sbin/chroot . /usr/sbin/userdel altlinux

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

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

echo 'Everything is done successfully!'
