#!/bin/sh
#
# Partition the USB stick -- the stick is assumed to be at least 3GB in size
#
# First delete all existing partitions
#
. ./config
. ./config2

# Check for tools needed
for i in fdisk gunzip blkid install-mbr sfdisk partprobe syslinux ; do
  if [ ! -e `which $i` ] ; then
    echo " "
    echo "$i does not seem to be installed; cannot continue."
    echo " "
    exit 1
  fi
done

if [ ! `whoami` = "root" ] ; then
  echo ""
  echo "You need to be root to run this shell script"
  echo ""
  exit 1
fi
if [ "x$USB_DEV" = "x" ] ; then
  if [ "x$1" = "x" ] ; then
     echo "You must supply the USB device name on the command line or in USB_DEV"
     exit 1
  else
     USB_DEV=$1
  fi
fi
echo "This script will distroy everything on $USB_DEV"
fdisk -l $USB_DEV
echo " "
echo "Answer yes to continue "
read a
if [ "$a" != "yes" ] ; then
  echo "Device $USB_DEV unchanged"
  exit 1
fi
sfdisk -l $USB_DEV >original-partitioning.txt
install-mbr ${USB_DEV}

fdisk $USB_DEV <<EOF
d
4
d
3
d
2
d
1
n
p
1

${SIZE_PART1}
t
c
a
1
n
p
2

${SIZE_PART2}
n
p
3


p
w
EOF
partprobe >/dev/null 2>&1
partprobe ${USB_DEV}1 >/dev/null 2>&1
umount ${USB_DEV}1 >/dev/null 2>&1
mkfs.vfat -F 32 -n xubuntu9 ${USB_DEV}1
partprobe >/dev/null 2>&1
umount ${USB_DEV}2 >/dev/null 2>&1
mkfs.ext3 -j -b 4096 -L casper-rw ${USB_DEV}2
# Do fs checking every 100 mounts or 360 days
tune2fs -c 100 -i 360 ${USB_DEV}2
partprobe >/dev/null 2>&1
umount ${USB_DEV}3
mkfs.ext3 -j -b 4096 -L bs-rescue ${USB_DEV}3
tune2fs -c 100 -i 360 ${USB_DEV}3
sync

echo "New partitioning is:"
fdisk -l ${USB_DEV}
syslinux ${USB_DEV}1
sync
partprobe >/dev/null 2>&1

echo "We're done, now it's a good time to unplug and replug your usb key"
echo "Then make sure that /media/bs-rescue is mounted before"
echo  "running the copy_bacula_to_usb_key script"
