#!/bin/sh
if [ "_$1" = "_" ]; then
  echo "Must supply device name, usually sdc, then x|[nox] icefs|[ext4]"
  exit
fi
if [ "`whoami`" != "root" ]; then
  echo "Must be run as root"
  su -c "$0 $1"
  exit
fi

umount /dev/$1*

gdisk -l /dev/$1
echo "The mount point /mnt/tmp must exist and be available for use." 
echo -n "Are you sure you want to proceed on this device [y/n]? " ; read ans
if [ "$ans" != "y" ]; then exit ; fi

./makedisk $1 _
sync
sleep 2
mkdir -p /mnt/tmp

echo "Copying ICEOS_BOOT partition"
mount /dev/${1}1 /mnt/tmp
tar -xzf iceboot.tz -C /mnt/tmp/
cp -pPf /mnt/tmp/EFI/BOOT/BOOTx64.efi-usb /mnt/tmp/EFI/BOOT/BOOTx64.efi
mv -f /mnt/tmp/etc/iceos.ISBOOT /mnt/tmp/etc/iceos.ISBOOT_
umount /mnt/tmp
sync

echo "Copying ICEOS_ROOT partition"
mount /dev/${1}2 /mnt/tmp
tar -xzf iceroot.tz -C /mnt/tmp/
umount /mnt/tmp
sync

echo "Copying ICEOS_USER partition"
mount /dev/${1}3 /mnt/tmp
if [ -e iceuser.tz  ]; then tar -xzf iceuser.tz  -C /mnt/tmp/ ; fi
if [ -e iceuserd.tz ]; then tar -xzf iceuserd.tz -C /mnt/tmp/ ; fi
if [ -e iceuserx.tz ]; then tar -xzf iceuserx.tz -C /mnt/tmp/ ; fi
umount /mnt/tmp
sync

echo "Copying ICEOS_DATA files"
mount /dev/${1}4 /mnt/tmp
chmod 777 /mnt/tmp/
for user in root iceman icemkr iceuser updates; do
  mkdir -p -m 755 /mnt/tmp/$user 
done
if [ -e iceinstaller.tar  ]; then cp iceinstaller.tar /mnt/tmp/updates/ ; fi

# these IDs are hardwired in ICEOS
chown 1000:100 /mnt/tmp/icemkr
chown 1001:100 /mnt/tmp/iceman
chown 1002:100 /mnt/tmp/iceuser
umount /mnt/tmp
sync

echo "Done creating live ICEOS image on $1"
