#!/bin/bash
echo "mmcinstall - Copy system partition to internal mmc device"
echo "Copyright (C) 2013 by Silvan Calarco <silvan.calarco@mambasoft.it>"
echo
SOURCEPART=`cat /proc/cmdline | sed "s|root=\([^[:space:]]*\).*|\1|"`
[ "$SOURCEPART" ] || {
   echo "ERROR: unable to detect root device; aborting."
   exit 1
}

cnt=0
grep mmcblk0p /proc/partitions | while read line; do
   set -- $line
   cnt=$((cnt + 1))
   size=$(($3 / 1024))
   echo "$cnt) $4 ($size MB)"
done

echo
while [ ! "$ans" ]; do
   echo -n "Please select target partition: "
   read ans
done

if [ "$ans" ]; then
   set -- `grep mmcblk0p /proc/partitions | tail -n +$ans | head -n 1`
   DESTPART="/dev/$4"
fi

[ -e $DESTPART ] || {
   echo "Error: destination device $DESTPART missing; aborting."
   exit 1
}

echo
echo -e -n "Ok to copy system from $SOURCEPART to $DESTPART?\nWARNING: all data on $DESTPART will be lost!\nPlease enter 'Y' to proceed: "
read ans

[ "$ans" = "Y" ] || exit 1

echo "Formatting $DESTPART"
mkfs.ext4 -L project $DESTPART || {
   echo "Error formatting $DESTPART; aborting."
   exit 1
}

echo -n "Copying $SOURCEPART filesystem to $DESTPART..."
mkdir -p /mnt/project-source
mount $SOURCEPART /mnt/project-source
mkdir -p /mnt/project
mount $DESTPART /mnt/project
cp -a /mnt/project-source/* /mnt/project/
umount $DESTPART
umount $SOURCEPART
rmdir /mnt/project-source
rmdir /mnt/project
echo
echo "Done."
