#!/bin/bash
set -e # fail on any error
mountpoint=/mnt/img

if [ -z "$1" ]; then
    echo "Usage: pi_create_image_from_img path/to/file.img"
    exit 1
fi

if [ ! -f "$1" ]; then
    echo "$1 not found"
    exit 1
fi

if [ ! -d "$mountpoint" ]; then
    echo "$mountpoint not found, creating"
    sudo mkdir -p "$mountpoint"
fi

imgpath="$(realpath $1)"
imgdir="$(dirname $imgpath)"
xzpath="$imgpath.xz"
renamepath="${imgpath:0:-4}_$(date -I).img.xz"
device="/dev/mapper/loop0p2"

sleepfive () {
    echo "Sleeping 5 seconds"
    sleep 5
}

echo -e "creating pi image from existing .img file $imgpath"

echo -e "\nsettings:\n\tmountpoint: $mountpoint\n\timgpath: $imgpath\n\timgdir: $imgdir\n\txzpath: $xzpath\n\trenamepath: $renamepath\n\tdevice: $device\n"

echo "changing directory to $imgdir"
cd "$imgdir"

echo "mapping $imgpath"
sudo kpartx -av "$imgpath"

sleepfive

echo "mounting $imgpath"
sudo mount "$device" "$mountpoint"

echo -e "now edit the image in another tab: $mountpoint\nENTER when done"
read teeeemp

sleepfive

echo "unmounting $mountpoint"
sudo umount "$mountpoint"

sleepfive

echo "unmapping $imgpath"
sudo kpartx -dv "$imgpath"

sleepfive

echo "shrinking $imgpath to $xzpath"
sudo pishrink -Z -r -v -a "$imgpath"

sleepfive

echo "testing image $xzpath"
sudo xz -t -v "$xzpath"

sleepfive

echo "renaming $xzpath to $renamepath"
sudo mv "$xzpath" "$renamepath"

echo "Delete $imgpath? y/n"
read delimg
if [[ "$delimg" =~ ^[yY] ]]; then
    echo "Deleting $imgpath"
    sudo rm -f "$imgpath"
fi

echo -e "\nDONEEE $renamepath\n"