#!/bin/bash

doRemove=0
lernstickEFIPartition=$(diskutil list "/dev/disk0" | grep "EFI - LERNS" | sed 's/.* //g' | grep -oE "disk0s[0-9]*")
containerToDelete=$(diskutil list "/dev/disk0" | grep "Apple_APFS" | grep '\b2\.5' | sed 's/.* //g' | grep -oE "disk0s[0-9]")

if [ -z "$lernstickEFIPartition" ];then
    echo "Couldn't find lernstick EFI volume"
    doRemove=1
fi

if [ -z "$containerToDelete" ];then
    echo "Couldn't find lernstick APFS container"
    doRemove=1
fi

if [ $doRemove -eq 0 ];then
    echo "This script remove the Lernstick OS installation from your disk."
    echo "It will affect your disk. "
    echo ""
    diskutil list "/dev/disk0"
    echo ""
    echo -n "Remove Lernstick OS container: "
    echo "${containerToDelete}"
    echo -n "Remove Lernstick OS volume: "
    echo "${lernstickEFIPartition}"
    echo ""
    echo "Press enter twice if you want to remove the Lernstick OS installation"
    echo "Press Control-C to exit."

    read
    read

    diskutil apfs deleteContainer "${containerToDelete}"
    diskutil eraseVolume free free "${lernstickEFIPartition}"

    cat > /tmp/uuids.txt <<EOF
3D3287DE-280D-4619-AAAB-D97469CA9C71
C8858560-55AC-400F-BBB9-C9220A8DAC0D
EOF

    diskutil apfs listVolumeGroups >> /tmp/uuids.txt

    cd /System/Volumes/iSCPreboot

    for i in ????????-????-????-????-????????????; do
        if grep -q "$i" /tmp/uuids.txt; then
            echo "Keep group file: $i"
        else
            echo "Remove group file: $i"
            rm -rf "$i" 2>/dev/null
        fi
    done
else
    echo ""
    echo "No Lernstick OS installation found"
fi

freeSpace=$(diskutil list /dev/disk0 | grep "(free space)" 2>/dev/null)
if [ $? -eq 0 ];then
    echo ""
    diskutil list /dev/disk0
    echo ""
    echo "Removing Lernstick OS installation left free space."
    echo "Get the disk space back: disk0s0"
    echo "It will affect your disk."
    echo ""
    echo "Press enter twice if you really want to continue."
    echo "Press Control-C to exit."

    read
    read

    diskutil apfs resizeContainer disk0s2 0
fi
