#!/bin/bash

# exit on error
set -e

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

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

# MBR and partition table
fdisk -l $DEV
dd if=mbr.bin of=$DEV
#echo w | fdisk $DEV
fdisk $DEV <<EOF
d
1
d
2
d
3
d
4
n
p
1

+63M
n
p
2


t
1
c
w
EOF

# 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 -f $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
