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

SVER='0.0.3'
RCFILE="/usr/lib/supportconfig/resources/supportconfig.rc"
OF='output-rmt.txt'

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

## Our own helper functions
validate_rpm_if_installed() {
  THISRPM=$1
  log_write $OF '#==[ Validating RPM ]=================================#'
  if rpm -q "$THISRPM" >/dev/null 2>&1; then
    if rpm -V $THISRPM >> ${LOG}/${OF} 2>&1; then
      log_write $OF "Status: Passed"
    else
      log_write $OF "Status: WARNING"
    fi
  else
    log_write $OF "package $THISRPM is not installed"
    log_write $OF "Status: Skipped"
  fi
  log_write $OF
}

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)

log_entry $OF note "Supportconfig Plugin for RMT, v${SVER}"
rpm_verify $OF rmt-server || exit 111

log_entry $OF note 'Packages'

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

log_entry $OF note "Configuration"
conf_files $OF "$CONF_FILES"

log_entry $OF note "SSL Configuration"
log_cmd $OF "ls -l /usr/share/rmt/ssl/"

if systemctl --quiet is-active nginx; then
  log_cmd $OF "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
    log_cmd $OF "openssl x509 -inform pem -noout -text -in $cert"
  done
fi

log_entry $OF note "Service Status"
for i in "${STATUS_UNITS[@]}"; do
  log_cmd $OF "systemctl status $i"
done

log_entry $OF note "Mirroring Status"
log_cmd $OF "rmt-cli products list"
log_cmd $OF "rmt-cli repos list"

log_entry $OF note "Service Logs"
for service in "${LOG_UNITS[@]}"; do
  log_cmd $OF "journalctl -n1000 -u $service"
done

log_entry $OF note "Custom Repos"
log_cmd $OF "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
    log_write $OF "Products bound to custom repo id: $custom"
    log_cmd $OF "rmt-cli repos custom products $custom"
  done
fi
_sanitize_file $OF

