#!/bin/sh

# This will clear everything on phone
# It will restore phone as it left factory

# Before doing the actual clean, make sure our factory snapshot is
# new enough and has tools to recover home partition
ROOT=$(grep "/dev/mmc.* / " /proc/mounts | cut -d " " -f1)
[ -z "$ROOT" ] && echo_g "Root not found??" && exit 1
mount -o subvolid=0 $ROOT /mnt/ || { echo "Can't mount /mnt" && exit 1; }
if [ -d /mnt/factory-\@ -a  -d /mnt/factory-\@home ] &&
   [ 0 -lt `grep -c  "FACTORY_CLEAN_CAPABLE_IMAGE_V2" /mnt/factory-\@/sbin/preinit` ] &&
   [ 0 -lt `grep -c  "subvol=\@home" /mnt/factory-\@/etc/fstab` ]; then
    # All is good for cleaning
    umount /mnt
else
    echo "Flashed recovery image is too old and does not support phone clearing. Can't do it"
    umount /mnt
    exit 1
fi

echo "Warning, this will clear the phone and you'll lose all contents"
echo "including photos, music, installed applications etc."
echo "Phone will be restored to same state as it left factory."
echo "Are you sure? (yes/no)"
read a 
if [ "$a" == "yes" ]; then
    /usr/lib/qt5/plugins/devicelock/encpartition --clear-device " " || { echo "Can't set the flag" && exit 1; }
    echo "Clearing the phone. Please wait..."
    echo "Phone will reboot (no UI) for the clean and then it will power off itself."
    echo "Whole process will take about 20s"
    reboot
    sleep 10
    sync
    reboot -f
else
    echo "Ok, let's forget it"
fi
