#!/bin/sh
such="root=/dev/mmcblk1"

echo ""
echo -e "\e[7mCopy EMMC to SD\e[0m"

grep -q $such /proc/cmdline
if [ $? == 0 ]; then
    bootpart="/dev/mmcblk1p1"
    bootdev="EMMC"
else
    bootpart="/dev/mmcblk0p1"
    bootdev="SD"
fi
                
if [ $bootdev == "SD" ]; then
    echo "System was booted from SD, copying Image from EMMC not possible ! ==> EXIT"
    exit 1
fi

if [ ! -b /dev/mmcblk0 ]; then
    echo -e "\e[31mNo SD Card insertd ! ==> EXIT\e[0m"
    exit 2
fi

echo -e "\e[31mSD card will be formatted, all Data on this Card will be deleted!!\e[0m"
echo ""
read -n 1 -p "are you sure? (y/n) : " antwort

if [ ${#antwort} == 0 ]; then
  antwort = "n"  
fi

if [ $antwort == "y" -o $antwort == "Y" ]; then
  echo -e "\nStart copying .."
else
  echo -e "\nEXIT on user reqest"
  exit 3
fi    

echo "Formatting SD ...."

fdisk /dev/mmcblk0 <<EOF
o
p
n
p
1

2048
t
e
a
1
n
p
2


p
w
EOF
umount /dev/mmcblk0p1
dd if=/dev/zero of=/dev/mmcblk0p1 bs=1024 count=1024
mkfs.vfat -F 16 /dev/mmcblk0p1
umount /dev/mmcblk0p2
dd if=/dev/zero of=/dev/mmcblk0p2 bs=1024 count=1024
mkfs.ext4 /dev/mmcblk0p2
# temp. mountdirectories
mkdir /tmp/boot
mkdir /tmp/bootdata
mkdir /tmp/rootfs
# mounten der Partitionen
mount /dev/mmcblk0p1 /tmp/boot
mount /dev/mmcblk0p2 /tmp/rootfs
mount /dev/mmcblk1p1 /tmp/bootdata
# daten kopieren
cp -f /tmp/bootdata/MLO /tmp/boot
cp -f /tmp/bootdata/*.dtb /tmp/boot
cp -f /tmp/bootdata/u-boot.img /tmp/boot
cp -f /tmp/bootdata/uImage /tmp/boot
#--- build rootfs -- make default sys dirs for rootfs
mkdir -p /tmp/rootfs/sys
mkdir -p /tmp/rootfs/proc
mkdir -p /tmp/rootfs/tmp/fontconfig
mkdir -p /tmp/rootfs/dev/pts
mkdir -p /tmp/rootfs/dev/shm
WRKDIR=`pwd`
cd /tmp/rootfs/dev
ln -s ../tmp/log ./log
cd $WRKDIR
for i in `seq 0 7` ; do 
  echo "usb$i"
  mkdir -p /tmp/rootfs/media/usb$i
done
mkdir -p /tmp/rootfs/mnt
#--- copy rootfs from SD
cd /
tar --exclude=./sys --exclude=./proc --exclude=./dev --exclude=./media --exclude=./tmp --exclude=./mnt -cf - . | (cd /tmp/rootfs && tar -xvf -)
#--- copy done
cd 
df -h
umount /dev/mmcblk0p1 /dev/mmcblk0p2 /dev/mmcblk1p1
