#!/bin/sh
set -e

IMAGE_URL="$1"
DISK="$2"
EXT="${IMAGE_URL##*.}"

echo "Downloading and writing to $DISK..."

case "$EXT" in
    zst) wget -O - "$IMAGE_URL" | zstd -d | dd of="$DISK" bs=1M status=progress ;;
    xz)  wget -O - "$IMAGE_URL" | xz -d | dd of="$DISK" bs=1M status=progress ;;
    gz)  wget -O - "$IMAGE_URL" | gzip -d | dd of="$DISK" bs=1M status=progress ;;
    bz2) wget -O - "$IMAGE_URL" | bzip2 -d | dd of="$DISK" bs=1M status=progress ;;
    tar) wget -O - "$IMAGE_URL" | tar -xvf - -C /mnt ;;
    *)   echo "Unsupported format"; exit 1 ;;
esac

sync
echo "Restore complete. Rebooting..."
reboot

