#!/bin/bash
#############################################################
# Name:        Supportconfig Plugin for RMT
# Description: Gathers important troubleshooting information
#              about RMT
# License:     GPLv2
# Author:      SCC Team <happy-customer@suse.de>
# Modified:    2018 April 18
#############################################################

SVER=0.0.2
RCFILE="/usr/lib/supportconfig/resources/scplugin.rc"

[ -s $RCFILE ] && . $RCFILE || { echo "ERROR: Initializing resource file: $RCFILE"; exit 1; }

## Our own helper functions
validate_rpm_if_installed() {
  THISRPM=$1
  echo "#==[ Validating RPM ]=================================#"
  if rpm -q "$THISRPM" >/dev/null 2>&1; then
    echo "# rpm -V $THISRPM"

    if rpm -V "$THISRPM"; then
      echo "Status: Passed"
    else
      echo "Status: WARNING"
    fi
  else
    echo "package $THISRPM is not installed"
    echo "Status: Skipped"
  fi
  echo
}

RPMLIST=(rmt-server nginx mariadb)

STATUS_UNITS=(rmt-server.service rmt-server-migration.service rmt-server-sync.timer rmt-server-mirror.timer mariadb.service nginx.service)

LOG_UNITS=(rmt-server.service rmt-server-migration.service rmt-server-sync.service rmt-server-mirror.service mariadb.service nginx.service)

CONF_FILES=(/etc/rmt.conf /etc/nginx/vhosts.d/rmt-server-http.conf /etc/nginx/vhosts.d/rmt-server-https.conf)

section_header "Supportconfig Plugin for RMT, v${SVER}"
if ! rpm -q rmt-server &>/dev/null; then
  echo -e "ERROR: RMT rpm package ('rmt-server') not installed\n"
  exit 111
fi

plugin_tag "Packages"
for pkg in "${RPMLIST[@]}"; do
  validate_rpm_if_installed "$pkg"
done

plugin_tag "Configuration"
pconf_files "$CONF_FILES"

plugin_tag "SSL Configuration"
plugin_command "ls -l /usr/share/rmt/ssl/"

if systemctl --quiet is-active nginx; then
  plugin_command "echo | openssl s_client -showcerts -servername localhost -connect localhost:443 2>/dev/null | openssl x509 -inform pem -noout -text"
else
  for cert in /usr/share/rmt/ssl/rmt-ca.crt /usr/share/rmt/ssl/rmt-server.crt; do
    plugin_command "openssl x509 -inform pem -noout -text -in $cert"
  done
fi

plugin_tag "Service Status"
for i in "${STATUS_UNITS[@]}"; do
  plugin_command "systemctl status $i"
done

plugin_tag "Mirroring Status"
plugin_command "rmt-cli products list"
plugin_command "rmt-cli repos list"

plugin_tag "Service Logs"
for service in "${LOG_UNITS[@]}"; do
  plugin_command "journalctl -n1000 -u $service"
done

plugin_tag "Custom Repos"
plugin_command "rmt-cli repos custom list"
custom_repos=$(rmt-cli repos custom list --csv 2>/dev/null | sed 1d | cut -d ',' -f 1)
if [ -n "$custom_repos" ]; then
  for custom in $custom_repos; do
    echo "Products bound to custom repo id: $custom"
    plugin_command "rmt-cli repos custom products $custom"
  done
fi
