#!/bin/bash
#RestoreScript für SDCards
#made by STP - tux-mamia Support
#Licence GPL
#Date: 14.02.2017
#Important: not tested!
set -e

DEV=$1
COUNT=0
TAROPT=xvfz
TAREND=tar.gz

if [ ! -d $PWD/backup ]; then
        echo "Backup directory does no exist!" 
        exit 1
fi


if [[ $(which test > /dev/null) == true ]]; then
        echo "Do yoe need test for this script!" 
        exit 1
fi

if [[ $USERNAME != root ]]; then
        echo "You have no root access. Please logon as root and retry!" 
        exit 1
fi

if [[ $# -eq 0 ]]; then
        echo "Please add the SDCard Device the command line to restore the SDCard!" 
        exit 1
fi

if [ ! -e $DEV ]; then
      echo "Device does not exist!"
      exit 1
fi


sfdisk $DEV < $PWD/backup/partitiontables #Partitinstabelle zurückspielen!
kpartx $DEV

if [[ ! -d $PWD/mnt ]]; then
	mkdir $PWD/mnt
fi

while [[ $COUNT -lt 2 ]]; do
  let COUNT=COUNT+1
  if [ ! -b $DEV$COUNT ]; then
    DEV=$DEV"p"
  fi
  if [[ $COUNT == 1 ]]; then
    mkfs.vfat -n PI_BOOT $DEV$COUNT
    mount $DEV$COUNT $PWD/mnt
    cd $PWD/mnt
    tar $TAROPT $OLDPWD/backup/thinpi$COUNT.$TAREND
    cd $OLDPWD
    umount $OLDPWD
  else
    mkfs.ext4 -L PI_ROOT $DEV$COUNT
    mount $DEV$COUNT $PWD/mnt
    cd $PWD/mnt
    tar $TAROPT $OLDPWD/backup/thinpi$COUNT.$TAREND
    cd $OLDPWD
    umount $OLDPWD
  fi
done

rm -rf $OLDPWD
exit 0
