#!/usr/bin/bash

get_config() {
	REBASE_HELPER_CONFIG_FILE="${REBASE_HELPER_CONFIG_FILE:-/etc/ublue-os/rebase_helper.json}"
	QUERY="$1"
	FALLBACK="$2"
	shift
	shift
	OUTPUT="$(jq -r "$QUERY" "$REBASE_HELPER_CONFIG_FILE" 2>/dev/null || echo "$FALLBACK")"
	if [ "$OUTPUT" == "null" ] ; then
		echo "$FALLBACK"
		return
	fi
	echo "$OUTPUT"
}

DX_HELPER_ENABLED="$(get_config '."dx-helper-enabled"' "true")"
IMAGE_BASE_NAME="$(get_config '."image-base-name"' "invalid-image-name")"

if [[ "$DX_HELPER_ENABLED" == 'false' || "$IMAGE_BASE_NAME" == "invalid-image-name" ]] ; then
  # FIXME: write this better
  cat <<EOF
The DX helper is not enabled here, the image most likely has some reason why it is disabled, check their documentation.
EOF
	exit 0
fi

# FIXME: have a way to depend on ujust on the spec
#shellcheck disable=1091
source /usr/lib/ujust/ujust.sh

CURRENT_IMAGE=$(rpm-ostree status -b --json | jq -r '.deployments[0]."container-image-reference"')

if /bin/grep -q "\-dx" <<< $CURRENT_IMAGE ; then
    CURRENT_STATE="enabled"
else
    CURRENT_STATE="disabled"
fi
echo "Developer mode is currently ${CURRENT_STATE}"
echo "Enable or Disable developer mode"
OPTION=$(Choose Enable Disable)
if [[ "${OPTION,,}" =~ ^enable ]]; then
    if [ "$CURRENT_STATE" = "enabled" ] ; then
        echo "You are already on a developer image"
        exit 0
    fi
    echo "Rebasing to a developer image"
    NEW_IMAGE=$(sed "s/$IMAGE_BASE_NAME/$IMAGE_BASE_NAME-dx/" <<< $CURRENT_IMAGE)
    rpm-ostree rebase $NEW_IMAGE && echo -e "\nUse \`ujust dx-group\` to add your user to the correct groups and complete the installation"
fi

if [[ "${OPTION,,}" =~ ^disable ]]; then
    if [ "$CURRENT_STATE" != "enabled" ]; then
        echo "You are not currently on a developer image"
        exit 0
    fi
    echo "Rebasing to a non developer image"
    # Remove -dx suffix from image, specifies ":" to mark the end of the image name
    NEW_IMAGE=$(sed "s/\-dx//" <<< $CURRENT_IMAGE)
    rpm-ostree rebase $NEW_IMAGE
fi
