#!/bin/sh

set -e

echo "POSTTRANS: Running script"

[ -f /etc/sysconfig/grafana-server ] && . /etc/sysconfig/grafana-server
[ -z "$GRAFANA_USER" ] && GRAFANA_USER="grafana"
[ -z "$GRAFANA_GROUP" ] && GRAFANA_GROUP="grafana"
[ -z "$GRAFANA_HOME" ] && GRAFANA_HOME="/usr/share/grafana"
[ -z "$DATA_DIR" ] && DATA_DIR="/var/lib/grafana"

START_GRAFANA_SERVICE=0
if ! [ -f "${DATA_DIR}"/is-fresh-rpm-install ] && [ "$RESTART_ON_UPGRADE" = "true" ]; then
  systemctl stop grafana-server.service > /dev/null 2>&1 || :
  START_GRAFANA_SERVICE=1
fi
rm -f "${DATA_DIR}"/is-fresh-rpm-install > /dev/null 2>&1 || :

# copy config files if missing
if [ ! -f /etc/grafana/grafana.ini ]; then
  echo "POSTTRANS: Config file not found"

  if [ -f /etc/grafana/grafana.ini.rpmsave ]; then
    echo "POSTTRANS: /etc/grafana/grafana.ini.rpmsave config file found."
    mv /etc/grafana/grafana.ini.rpmsave /etc/grafana/grafana.ini
    echo "POSTTRANS: /etc/grafana/grafana.ini restored"

    if [ -f /etc/grafana/ldap.toml.rpmsave ]; then
      echo "POSTTRANS: /etc/grafana/ldap.toml.rpmsave found"
      mv /etc/grafana/ldap.toml.rpmsave /etc/grafana/ldap.toml
      echo "POSTTRANS: /etc/grafana/ldap.toml restored"
    fi

    echo "POSTTRANS: Restoring config file permissions"
    chown -Rh root:$GRAFANA_GROUP /etc/grafana/*
    chmod 755 /etc/grafana
    find /etc/grafana -type f -exec chmod 640 {} ';'
    find /etc/grafana -type d -exec chmod 755 {} ';'
  fi
fi

# Bundled plugins must live under $DATA_DIR (writable by grafana) so the
# plugin auto-updater can replace them; the service points
# paths.bundled_plugins there. Copy instead of move so the packaged files
# stay in place and `rpm -V` stays clean. Only replace the existing
# bundled plugins when the package actually contains plugin definitions.
if [ -d "$GRAFANA_HOME/data/plugins-bundled" ] && \
   find "$GRAFANA_HOME/data/plugins-bundled" -type f -name plugin.json -print | grep -q .; then
  mkdir -p "${DATA_DIR}"
  rm -rf "${DATA_DIR:?}/plugins-bundled"
  cp -a "$GRAFANA_HOME/data/plugins-bundled" "$DATA_DIR"
  chown -R "$GRAFANA_USER":"$GRAFANA_GROUP" "$DATA_DIR/plugins-bundled"
fi

if [ "$START_GRAFANA_SERVICE" -eq 1 ]; then
  systemctl daemon-reload || :
  systemctl start grafana-server.service > /dev/null 2>&1 || :
fi
