#!/bin/bash

img=${1?usage: $0 input_image}
outdev=${2-/dev/mmcblk0}
ext="${img##*.}"

echo "$img to $outdev"

if [ "$UID" -ne 0 ]; then
    echo "Error: must be root" >&2
    exit 1
fi

if [ ! -f "$img" ]; then
    echo "Error: File $img not found">&2
    exit 1
fi


if [ "$ext" = "xz" ]; then
    xz -dc "$img" | dd if=/dev/stdin of="$outdev" status=progress conv=fsync bs=4M
elif [ "$ext" = "gz" ]; then
    gunzip -c "$img" | dd if=/dev/stdin of="$outdev" status=progress conv=fsync bs=4M
 
else
    dd if="$img" of="$outdev" status=progress conv=fsync bs=4M
fi


sync; sync; sync

echo "Done"