#!/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 the already-provisioned desktop system on $(c /dev/sdx).

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

  NOTE:
    Run $(g tl-hw-prepare) on $(c /dev/sdx) first to prepare the partition layout
    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 "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"
}

say "Modifying recovery ISO with new id & label"
{
  run sudo xorriso -dev "$ISO" -volid "recovery$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-hw-update-bootloader" "$DISK"
