#/bin/bash
# usage:
##  create image name format YYYY-MM-DD-HHMM-S.<TAG>.img/.xz/.info
###  pi_create_image <image name tag no spaces>
##  generate sha256 of uncompressed image
###  pi_create_image <image name tag no spaces> true
timestamp=`date +"%Y-%m-%d-%H%M-%S"`

# handle filename
if [ -z "$1" ]; then
    tag=$timestamp-pi
else
    tag=$timestamp-$1
fi

# fiel paths
imgname=$tag.img
xzname=$imgname.xz # already has da pwd from imgname
info=$xzname.info
checksums=sha256sum-$tag.sha256

# create info file
touch $info

# get real username (not root) if run with sudo
if [ ! -z $SUDO_USER ]; then
    username=$SUDO_USER
else
    username=$USER
fi

# get disk
lsblk
echo "Enter disk name (including /dev/) ex /dev/sdb"
read dadisk

# start
webhook "starting copy $dadisk to $imgname to $xzname at $(date)($(date +%s))\ninfo: $info" true

# copy disk
sudo dd if=$dadisk of=$imgname bs=4M status=progress
imgsize=$(du -h $imgname)
imgbytes=$(du - $imgname)

webhook "Copied the disk to $imgname size $imgsize ($imgbytes)"

if [ ! -z "$2" ]; then
    # img sha256
    webhook "creating sha256 checksum of $imgname"
    img_checksum=$(sha256sum $imgname)
    echo "$img_checksum" | tee -a $info
    webhook "sha256 of $imgname is $img_checksum, saved to $info"
fi

# shrink and compress the image
# -Z xz image after shrinking
# -a use multiple cores for xz
# -v verbose
# -r use advanced filesystem repair if normal one fails
webhook "shrinking and compressing the image"
sudo pishrink -Z -r -v -a $imgname
xzsize=$(du -h $xzname)
xzbytes=$(du -b $xzname)

# log filesizes
webhook "saving sizes imgsize: $imgsize / $imgbytes xzsize: $xzsize / $xzbytes to $info"
echo -e "imgsize: $imgsize ($imgbytes)\nxzsize: $xzsize ($xzbytes)" | tee -a $info

# change archive to be friendly perms
webhook "changing perms"
sudo chown $username:$username $xzname

# test archive with xztools 
webhook "testing archive $xzname"
xz -t $xzname
ret=$?

# if test fails
if [ $ret -gt 0 ]; then
    webhook "FAIL! ARCHIVE DES NOT CHECK return code: $ret EXITING"
    exit 1
# if test succeeds
else
    webhook "Archive Test SUCCESS"
fi

# always generate last checksum
webhook "calculating xz checksum"
xz_checksum=$(sha256sum $xzname)
echo "$xz_checksum" | tee -a $info
webhook "xz checksum $xz_checksum"

# finish and notify
webhook "DONE\n\tdisk: $dadisk\n\timgname: $imgname size $imgsize / $imgbytes\n\txzname: $xzname size $xzsize / $xzbytes\n\tsha256 of $xzname: $xz_checksum\n\tinfo file: $info" true

# schedule reboot in 1 minute
sudo shutdown -r +1