#!/usr/bin/bash
#
# Insights proxy Service
#
export VERBOSE="n"
RHPROXY_NAME="Insights proxy"
RHPROXY_SERVICE="rhproxy"
RHPROXY_PKG_ROOT="${RHPROXY_PKG_ROOT:-/usr/share/${RHPROXY_SERVICE}}"

CONFIG_PATH="${RHPROXY_PKG_ROOT}/config"
ENV_PATH="${RHPROXY_PKG_ROOT}/env"
DOWNLOAD_PATH="${RHPROXY_PKG_ROOT}/download"

RHPROXY_USER_PATH="${HOME}/.local/share/rhproxy"
ENV_USER_PATH="${HOME}/.config/rhproxy/env/"
SYSTEMD_USER_PATH="${HOME}/.config/containers/systemd/"

CERTS_SHARE_PATH="${RHPROXY_USER_PATH}/certs"
DOWNLOAD_SHARE_PATH="${RHPROXY_USER_PATH}/download"

if [ "${1}" == "-v" ] || [ "${1}" == "--verbose" ]; then
  VERBOSE="y"
  shift
fi

COMMAND="${1}"
shift

function debug_msg {
  if [ "${VERBOSE}" == "y" ]; then
    echo "$@"
  fi
}

if [ "$(id -u)" -eq 0 ]; then
  echo "${RHPROXY_SERVICE} must not run as root."
  exit 1
fi

if [ -z "${XDG_RUNTIME_DIR}" ]; then
  export XDG_RUNTIME_DIR=/run/user/$UID
fi

function copy_container {
  container_config="${1}"
  target_dir="${2}"
  container_file=$(basename "${container_config}")
  debug_msg "Copying ${container_config} ${target_dir} ..."
  cp "${container_config}" "${target_dir}/${container_file}"
}

function copy_env {
  env_config="${1}"
  target_dir="${2}"
  env_file=$(basename "${env_config}")
  env_unit="$(cat "${env_config}")"
  debug_msg "Copying ${env_config} ${target_dir} ..."
  echo "${env_unit}" >"${target_dir}/${env_file}"
}

function update_download_files {
  debug_msg "Updating download files in ${DOWNLOAD_SHARE_PATH} ..."
  mkdir -p "${DOWNLOAD_SHARE_PATH}/bin"

  CONFIG_CLIENT="bin/configure-client.sh"
  debug_msg "Copying ${CONFIG_CLIENT} ..."

  export RHPROXY_SERVICE_PORT
  RHPROXY_SERVICE_PORT="$(grep '^RHPROXY_SERVICE_PORT=' "${ENV_USER_PATH}/rhproxy.env" | cut -f2 -d=)"

  envsubst "\$RHPROXY_SERVICE_PORT}" \
    < "${DOWNLOAD_PATH}/${CONFIG_CLIENT}.template" \
    > "${DOWNLOAD_SHARE_PATH}/${CONFIG_CLIENT}"

  chmod 755 "${DOWNLOAD_SHARE_PATH}/${CONFIG_CLIENT}"
}

if [ "${COMMAND}" == "install" ]; then

  mkdir -p "${CERTS_SHARE_PATH}"
  mkdir -p "${DOWNLOAD_SHARE_PATH}"

  systemctl --user reset-failed

  echo "Installing ${RHPROXY_NAME} configuration files ..."
  mkdir -p "${ENV_USER_PATH}"
  mkdir -p "${SYSTEMD_USER_PATH}"

  for container_file in "${CONFIG_PATH}"/*.container; do
    copy_container "${container_file}" "${SYSTEMD_USER_PATH}"
  done

  for env_file in "${ENV_PATH}"/*.env; do
    copy_env "${env_file}" "${ENV_USER_PATH}"
  done

  for servers_file in redhat.servers epel.servers; do
    copy_env "${ENV_PATH}/${servers_file}" "${ENV_USER_PATH}"
  done

  # Only copy the mirror servers if it does not exist from earlier installations
  if [ ! -f "${ENV_USER_PATH}/mirror.servers" ]; then
    copy_env "${ENV_PATH}/mirror.servers" "${ENV_USER_PATH}"
  fi

  echo "Generate the ${RHPROXY_NAME} service ..."
  systemctl --user daemon-reload

  echo "Enabling Lingering for user ${USER} ..."
  loginctl enable-linger "${USER}"

  update_download_files

  echo "${RHPROXY_NAME} Installed."
  exit 0
fi

if [ "${COMMAND}" == "uninstall" ]; then

  echo "Stopping ${RHPROXY_NAME} ..."
  systemctl --user stop rhproxy

  echo "Removing ${RHPROXY_NAME} Service ..."
  rm -f "${XDG_RUNTIME_DIR}"/systemd/generator/rhproxy-*.service
  rm -f "${SYSTEMD_USER_PATH}"/rhproxy*.container
  rm -f "${ENV_USER_PATH}"/*.env

  systemctl --user daemon-reload
  systemctl --user reset-failed

  if [ "${1}" == "-f" ]; then
    echo "Deleting ${RHPROXY_NAME} Data ..."
    echo "   Removing ${CERTS_SHARE_PATH} ..."
    rm -rf "${CERTS_SHARE_PATH}"
    echo "   Removing ${DOWNLOAD_SHARE_PATH} ..."
    rm -rf "${DOWNLOAD_SHARE_PATH}"
  fi

  echo "Disabling Lingering for user ${USER} ..."
  loginctl disable-linger "${USER}"

  echo "${RHPROXY_NAME} Uninstalled."
  exit 0
fi

if [ "${COMMAND}" == "update" ]; then
  echo "Updating download files for the ${RHPROXY_NAME} service ..."

  update_download_files
  exit 0
fi

if [ "${COMMAND}" == "start" ]; then
  echo "Starting the ${RHPROXY_NAME} service ..."
  systemctl --user daemon-reload
  systemctl --user start ${RHPROXY_SERVICE}.service

  update_download_files
  exit 0
fi

if [ "${COMMAND}" == "stop" ]; then
  echo "Stopping the ${RHPROXY_NAME} service ..."
  systemctl --user stop ${RHPROXY_SERVICE}.service
  exit 0
fi

if [ "${COMMAND}" == "restart" ]; then
  echo "Re-start the ${RHPROXY_NAME} service ..."
  systemctl --user daemon-reload
  systemctl --user restart ${RHPROXY_SERVICE}.service

  update_download_files
  exit 0
fi

if [ "${COMMAND}" == "status" ]; then
  systemctl --user status ${RHPROXY_SERVICE}.service
  exit 0
fi

echo "Usage: ${RHPROXY_SERVICE} [-v | --verbose] <command>"
echo ""
echo "Where <command> is one of:"
echo "  install           - Install ${RHPROXY_NAME}"
echo "  uninstall [-f]    - Uninstall ${RHPROXY_NAME}"
echo "                      specify -f to force remove the certs and download data"
echo ""
echo "  start             - Start the ${RHPROXY_NAME} Service"
echo "  stop              - Stop the ${RHPROXY_NAME} Service"
echo "  restart           - Re-start the ${RHPROXY_NAME} Service"
echo "  status            - Display Status of the ${RHPROXY_NAME} Service"
echo ""
echo "  update            - Update download files"

exit 1
