#!/bin/bash
set -euo pipefail

# shellcheck disable=SC2140
EPORTAL_URL="<!--# echo var="orig_scheme" -->://<!--# echo var="http_host" -->"

ENV_FILE=/etc/sysconfig/tuxcare/eportal.env
mkdir -p "$(dirname "$ENV_FILE")"

## dump env file content
cat << EOF > "$ENV_FILE"
echo "Registering host with $EPORTAL_URL ..."

curl --no-progress-meter -X POST "$EPORTAL_URL/admin/api/tuxcare/register.shell" \
     --data-urlencode "key=\$LICENSE" \
     --data-urlencode "hostname=\$HOSTNAME" \
     -o /root/.eportal.tuxcare.tmp

. /root/.eportal.tuxcare.tmp

if [ -z "\${EPORTAL_SERVER_ID:-}" ]; then
  echo Registration failed
  exit 1
fi

EPORTAL_URL="$EPORTAL_URL"
EPORTAL_TUXCARE_REPO="$EPORTAL_URL/patchserver/tuxcare/"
CLN_TUXCARE_TOKEN="\$EPORTAL_SERVER_ID"
EOF

## install tuxcare
dnf install -y "$EPORTAL_URL/patchserver/tuxcare/tuxcare-release-latest-$(rpm --eval %almalinux.%_arch).rpm"

echo "Done. To register the host use 'tuxctl --license-key <KEY>' command."
