#!/bin/bash
#
# update.sh
#
# This script mounts TempleOs C drive into a temporary mount folder, cp's the new Theme.HC file and checks if it's included in HomeSys.HC
#
# WARNING:
# This script could vary given the TempleOs instalation and virtualization method
# Given the ""intrusive"" tasks performed by this script, it's highly recommended to read it first and change everything accordingly

set -e

# Usage check
if [[ $# -ne 2 ]]; then
  echo -e "${YELLOW}Usage:${NC} $0 <templeos-image> <mount-point>"
  echo -e "Example: $0 templeos.img /tmp/templeos"
  exit 1
fi

IMAGE="$1"
MOUNT_POINT="$2"
SCRIPT_DIR="$(dirname "$0")"

echo "Mounting TempleOs's C drive into "$MOUNT_POINT" ..."
mkdir -p "$MOUNT_POINT"
guestmount -a "$IMAGE" -m /dev/sda1 "$MOUNT_POINT"

# Auto-clean on exit
cleanup() {
  echo -e "Unmounting ..."
  guestunmount "$MOUNT_POINT"
}
trap cleanup EXIT

echo "Replacing the Theme.HC file ..."
cp "$SCRIPT_DIR/Theme.HC" "$MOUNT_POINT/Home/Theme.HC"

HOMESYS="$MOUNT_POINT/Home/HomeSys.HC"
if grep -q '#include "~/Theme.HC"' "$HOMESYS"; then
  echo -e "Theme.HC is already included in HomeSys.HC."
else
  echo -e "Theme.HC is NOT included in HomeSys.HC."
  echo -e "You should add this line to it manually:"
  echo '#include "~/Theme.HC"'
fi

echo -e "Done. You may now boot into TempleOS."
