#! /bin/sh

# For debugging.
#exit 0

set -e

device=$1
swap_device=${device}1
fs_device=${device}2

test -e $device || exit 1

# First of all, stop everything.
/etc/init.d/erp5cdtool stop || true

# Make sure the swap is not already used
/sbin/swapoff -a

# Work around Linux bugs.
sync; sync; sync
sleep 5

# Now the dangerous operation.
/usr/sbin/parted --script $device mklabel msdos
max=`/usr/sbin/parted --script $device print | grep "Disk" | awk '{print $3}'`
/usr/sbin/parted --script $device mkpart primary linux-swap 0 1024
/usr/sbin/parted --script $device mkpart primary xfs 1024 $max

# Work around Linux bugs.
sync; sync; sync
sleep 5

# Format the partitions.
/sbin/mkswap $swap_device
/sbin/mkfs.xfs -f -L "ERP5" $fs_device

# Turn on the swap partition to avoid possible memory exaustion.
/sbin/swapon $swap_device

# This does everything.
/root/persistent.sh $fs_device

# Finish.
/sbin/swapoff $swap_device || true

exit 0