#!/bin/bash
set -v

# run with super user privileges

if [ -e /dev/mmcblk0p3 ]; then exit 0; fi

tot=`blockdev --getsize64 /dev/mmcblk0`
part=`blockdev --getsize64 /dev/mmcblk0p2`
ratio=`expr $tot / $part`
if [ $ratio -eq 1 ]; then
    echo "fully expanded 2 partition disk. no space for third partition. bailing."
    exit 0
fi

sed -e 's/\s*\([\+0-9a-zA-Z]*\).*/\1/' << EOF | fdisk /dev/mmcblk0
#d # delete partition
#3 # delete partition number 3
n # new
p # primary
3 # partition number 3
8881744 # first free sector
#976773167 # last free sector
# (y # remove signature ON NON VIRGIN SSD!)
w # write out, sync and quit
EOF
# this may complain about needing partprobe, so don't check return code

partprobe /dev/mmcblk0
ret=$?
if [ $ret -ne 0 ]; then
    echo partprobe returned $ret
    exit $ret
fi

# 2. make the filesystem on the new data partition.. forcibly
mkfs.ext4 -FF -L data /dev/mmcblk0p3
ret=$?
if [ $ret -ne 0 ]; then
    echo mkfs.ext4 returned $ret
    exit $ret
fi

# 3. mount this puppy, no need to reboot
mount -o defaults,noatime /dev/mmcblk0p3 /media
ret=$?
if [ $ret -ne 0 ]; then
    echo mount returned $ret
    exit $ret
fi

mkdir -p /media/internal
ret=$?
if [ $ret -ne 0 ]; then
    echo "mkdir returned $ret"
    exit $ret
fi

# 4. copy hidden user and factory data trees to data partition
cp -r /home/sysop/.internal/* /media/internal
ret=$?
if [ $ret -ne 0 ]; then
    echo "cp returned $ret"
    exit $ret
fi

# 5. remount system partition / .. we're gonna mod it.
mount -o remount,rw,noatime /
ret=$?
if [ $ret -ne 0 ]; then
    echo "remount returned $ret"
    exit $ret
fi

# 6. add entry in fstab for the new partition
printf "/dev/mmcblk0p3  /media ext4    defaults,noatime        0       3\n" >> /etc/fstab
ret=$?
if [ $ret -ne 0 ]; then
    echo "fstab echo returned $ret"
    exit $ret
fi

mkdir -p /media/usb/.usb0
mkdir -p /media/usb/.usb1
mkdir -p /media/usb/.usb2
mkdir -p /media/usb/.usb3

# 7. sanity check
touch /tmp/wedidit
