#!/bin/sh
# installs a rootfs tar archive from OpenADK onto a disk
# lemote yeelong specific installer

check_exit() {
        if [ $? -ne 0 ];then
                echo "Installation failed."
                exit 1
        fi
}

if [ -z $1 ];then
        printf "Please give your root tar archive as parameter\n"
        exit 1
fi

printf "Creating partitions ...\n"
parted -s /dev/sda mklabel msdos
check_exit
sleep 2
maxsize=$(env LC_ALL=C parted /dev/sda -s unit cyl print |awk '/^Disk/ { print $3 }'|sed -e 's/cyl//')
rootsize=$(($maxsize-2))
start=0
rootp=1
cfgfsp=2

parted -s /dev/sda unit cyl mkpart primary ext2 $start $rootsize
check_exit
mke2fs -q /dev/sda1
check_exit
parted -s /dev/sda unit cyl mkpart primary fat32 $rootsize $maxsize
check_exit
parted -s /dev/sda set $rootp boot on
check_exit
sfdisk --change-id /dev/sda $cfgfsp 88 >/dev/null 2>&1
check_exit
# settle down
sleep 2
mount -t ext2 /dev/sda$rootp /mnt
check_exit
printf "Extracting install archive ...\n"
tar -C /mnt -xzpf $1
check_exit
chmod 1777 /mnt/tmp
chmod 4755 /mnt/bin/busybox

cat << EOF > /mnt/boot/boot.cfg
default 0
timeout 3
showmenu 1
title OpenADK
        kernel (wd0,0)/boot/kernel
        args root=/dev/sda1 ro panic=10
}
EOF

umount /mnt
printf "Successfully installed. You can reboot now.\n"
exit 0
