#!/bin/bash

# exit on error
set -e

# set target device (SD card)
DEV=/dev/sdX

# mount dir
MNT=mnt
if [ ! -d $MNT ]
  then
    mkdir $MNT
fi

# MBR and partition table
dd if=mbr.bin of=$DEV conv=nocreat
fdisk -l $DEV
echo w | fdisk $DEV

# boot partition
mkfs.vfat ${DEV}1
mount ${DEV}1 $MNT
pv boot.tgz | tar -C $MNT -zx
umount $MNT

# root partition
mkfs.ext4 -E stride=2,stripe-width=1024 -b 4096 ${DEV}2
mount ${DEV}2 $MNT
pv root.tgz | tar -C $MNT -zx
# remove DB dump
rm $MNT/opt/flexim/dump/*
# remove replication client ID
perl -pe 's/(replication.id.*?value=\")[^\"]+/$1/' -i $MNT/etc/tomcat7/Catalina/localhost/topeni-server.xml
umount $MNT

# sync
sync
