#!/bin/bash
set -e

PACKAGE_MANAGER=""
determine_package_manager() {
  local OS_NAME=$(grep ^NAME /etc/os-release)
  local OS_VERSION=$(grep ^VERSION_ID /etc/os-release | cut -d'=' -f2)
  if [[ ! -z "$(echo "${OS_NAME}" | egrep -i "centos")" ]] && [ $OS_VERSION == '"7"' ]; then
    PACKAGE_MANAGER="yum"
  elif [[ ! -z "$(echo "${OS_NAME}" | egrep -i "centos|rocky|fedora|Red Hat|Oracle Linux")" ]]; then
    PACKAGE_MANAGER="dnf"
  elif [[ ! -z "$(echo "${OS_NAME}" | egrep -i "debian|ubuntu")" ]]; then
    PACKAGE_MANAGER="apt"
  elif [[ ! -z "$(echo "${OS_NAME}" | egrep -i "opensuse|SLES")" ]] ; then
    PACKAGE_MANAGER="zypper"
  else
    echo "Unexpected OS name $OS_NAME. Please contact Quobyte support with the content of /etc/os-release."
    exit 1
  fi
}

run_update() {
  determine_package_manager
  case $PACKAGE_MANAGER in
    "yum")
    yum update -y quobyte-server
    ;;
    "dnf")
    dnf update -y quobyte-server
    ;;
    "apt")
    DEBIAN_FRONTEND=noninteractive apt install -qy quobyte-server
    ;;
    "zypper")
    zypper update -y quobyte-server
    ;;
    *)
    echo "Unexpected package manager ($PACKACK_MANAGER).  Please contact Quobyte support with the content of /etc/os-release."
  esac
}

if [ "$#" -eq 1 ] && [ "$1" == "check" ]; then
  determine_package_manager
  test -n "$PACKAGE_MANAGER"
  echo $PACKAGE_MANAGER
  exit 0
fi

if [ "$#" -eq 1 ] && [ "$1" == "status" ]; then
  systemctl show --property=ActiveState update-quobyte-server  | grep -vq ActiveState=failed
  exit $?
fi

run_update
systemd-notify --ready
