#!/usr/bin/env bash

# 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

VERSION="$1" # Version of this ISO (x.x.x)
if [ -z "$VERSION" ] || [ -n "$HELP" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  say "
  $(r TODO:)
    $(r This command needs to be ported from Void to Artix)

  USAGE:
    $(g "${BASH_SOURCE##*/}")  $(c 0.0.0)

  DESCRIPTION:
    $(g "${BASH_SOURCE##*/}") creates a new, bootable-able ISO
    for installation and maintenance of TechLit systems.

    The version specified ($(c 0.0.0)) will be written to the ISO.

  NOTE:
    Use $(c "tl-comp-*") to distribute the boot-able ISO after creation.
"
  exit 1
fi

# Exit now if components are missing
assert-fetched recovery void-mklive

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

say "Entering $(c void-mklive) (and leaving on exit or error)"; {
  cleanup() {
    say "Leaving $(c void-mklive)"
    if dirs | grep -q "$ROOT/srv/void-mklive"; then
      run popd || exit 1
    fi
  }
  run pushd "$ROOT/srv/void-mklive" || exit 1
}

say "Creating a shim for $(c void-mklive) to run $(c tl-bootstrap-recovery)"
SHIM="/tmp/tl-bootstrap-recovery-shim"
run write "$SHIM" "'$ROOT/bin/tl-bootstrap-recovery' \"\$ROOTFS\" '$VERSION'"

say "Creating recovery ISO (this may take a while)"; {
  if ! [ -f "$ROOT/srv/void-mklive/mklive.sh" ]; then
    ( cd "$ROOT/srv/void-mklive" && make )
  fi

  export ROOT VERSION
  run sudo -E ./mklive.sh \
    -a x86_64 \
    -r "https://repo-de.voidlinux.org/current/nonfree" \
    -r "https://repo-de.voidlinux.org/current" \
    -r "http://void.techlitafrica.org/xbps/nonfree" \
    -r "http://void.techlitafrica.org/xbps" \
    -d "$ROOT/roles/global/xbps-keys" \
    -x "$SHIM" \
    -o "recovery.iso" \
    -T "TechLit Recovery v$VERSION"

  say "Moving $(c "v$VERSION") into $(c recovery) repo"
  run sudo mv -f "$ROOT/srv/void-mklive/recovery.iso" "$ROOT/srv/recovery/v$VERSION.iso"
  run sudo chown "$(id -u):$(id -g)" "$ROOT/srv/recovery/v$VERSION.iso"
}

# Update repo status
run append "$ROOT/srv/.tl-repo/recovery.local" "$VERSION"

# Unmount system and quiet exit hook
cleanup; cleanup() { :; }
say "Done."
