#!/usr/bin/env bash
# vim:et:ts=2:sts=2:sw=2

# Get absolute repository root (especially when symlinked)
ROOT="$(realpath "$(dirname "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")")")"

# Load accompanying bash library
source "$ROOT/lib/lib.bash"

# Exit now if run as root user
assert-is-user

# Path to USB disk
DISK="$1"
VERSION="${2:-"$("$ROOT/bin/tl-comp-latest" recovery)"}"
if [ -z "$DISK" ] || [ -n "$HELP" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  say "
  USAGE:
    $(g "${BASH_SOURCE##*/}")  $(c /dev/sdx)  [$(c version)]

  DESCRIPTION:
    $(g "${BASH_SOURCE##*/}") clones the recovery ISO with the version given
    ($(c version)) into already-provisioned installer USB on $(c /dev/sdx).

    The lastest version will be used if no version is given.

  NOTE:
    Run $(g tl-usb-prepare) on $(c /dev/sdx) first to prepare the disk and
    clone required components before writing the recovery ISO.
  "
  exit 1
fi

say "This script will need root access via $(c sudo)"
sudo echo thank you

ISO="/srv/recovery/v$VERSION.iso"  # ISO to use
PREFIX="${PREFIX:-"$(mktemp -d)"}" # Mountpoint to use

# partition infix
[[ "$DISK" =~ mmc ]] || [[ "$DISK" =~ nvm ]] && p=p || p=

say "Running checksums on $(c "$ISO")"
if (cd /srv/recovery && ! sha256sum -c "v$VERSION.sha256"); then
  say "Checksum failed for $(c "$ISO")"
  exit 1
fi

say "This script will need root access via $(c sudo)"
sudo echo thank you

say "Mounting system (and un-mounting on errors or exit)"
{
  cleanup() {
    say "Un-mounting system"
    run sudo umount -qR "$PREFIX"
  }
  run sudo mount "$DISK$p"4 "$PREFIX"
  run sudo rm -df "$PREFIX/lost+found"
}

# NOTE: Not working on artix iso
# say "Modifying recovery ISO with new id & label"; {
#   run sudo xorriso -dev "$ISO" -volid "installer$VERSION"
#   run sudo xorriso -dev "$ISO" -volume_date uuid "$(date +"%Y%m%d%H%M%S%C")"
# }

say "Copying ISO"
run sudo dd if="$ISO" of="$DISK$p"3 status=progress

# Handoff to grub installer
cleanup
cleanup() { :; }
sudo "$ROOT/bin/tl-usb-update-bootloader" "$DISK"
