#!/usr/bin/env bash
set -Eeuo pipefail

usage() {
  red "Missing argument $1.\n"
  cat <<EOF
Usage:
    burn.sh <NIXOS_URL> <USB_STICK>

      Arguments:
        NIXOS_URL         Download URL for NixOS ISO to be installed. Can be found at https://nixos.org/nixos/download.html
        USB_STICK         File descriptor of USB stick where to burn the ISO into. Use lsblk or similar tools to get it's name.

Examples:
    Download NixOS 19.03 x86_64 minimal and burn it into stick on /dev/sdb:
        NIXOS_URL='https://releases.nixos.org/nixos/19.03/nixos-19.03.172764.50d5d73e22b/nixos-minimal-19.03.172764.50d5d73e22b-x86_64-linux.iso'
        burn.sh "\$NIXOS_URL" /dev/sdb
EOF
}

NIXOS_URL="${1:-}"
USB_STICK="${2:-}"
ISO_PATH='/tmp/nixos.iso'

[[ -z "${NIXOS_URL}" ]] && {
  usage 'NIXOS_URL'
  exit 2
}

[[ -z "${USB_STICK}" ]] && {
  usage 'USB_STICK'
  exit 2
}

yellow "Downloading NixOS ISO..."
wget -cO "${ISO_PATH}"        "${NIXOS_URL}"
wget -cO "${ISO_PATH}.sha256" "${NIXOS_URL}.sha256"
diff <(sha256sum "${ISO_PATH}" | awk '{print $1}') <(awk '{print $1}' < "${ISO_PATH}.sha256") || {
  red "SHA256 didn't match!"
  exit 1
}
green "Done. SHA256 match."

yellow "Writing ISO image to ${USB_STICK}. We'll need sudo for it..."
umount "${USB_STICK}1" ||:
blue "$(du -hs /tmp/nixos.iso)"
sudo dd if="${ISO_PATH}" of="${USB_STICK}" status=progress
green "Done. You can remove the USB stick ${USB_STICK} with no unmounting required."
