#!/bin/bash
#
# Deb post-installation script for a Fleetspeak-enabled GRR client.
#
# Disables any existing legacy [non-Fleetspeak] service and restarts
# Fleetspeak.

set -e

if [[ "%(ClientBuilder.fleetspeak_bundled)" != "True" ]]; then
  if [[ -d /run/systemd/system ]]; then
    deb-systemd-invoke stop "%(ClientBuilder.package_name).service" >/dev/null 2>&1 || true
    deb-systemd-helper purge "%(ClientBuilder.package_name).service" >/dev/null 2>&1 || true
  else
    invoke-rc.d "%(ClientBuilder.package_name)" stop >/dev/null 2>&1 || true
  fi

  # Delete systemd config file if it still exists.
  if [[ -e "/lib/systemd/system/%(ClientBuilder.package_name).service" ]]; then
    rm -f "/lib/systemd/system/%(ClientBuilder.package_name).service" >/dev/null 2>&1 || true
    systemctl --system daemon-reload >/dev/null 2>&1 || true
  fi

  # Delete sysvinit service file, and all its /etc/rc${runlevel}.d links.
  if [[ -e "/etc/init.d/%(ClientBuilder.package_name)" ]]; then
    rm -f "/etc/init.d/%(ClientBuilder.package_name)" >/dev/null 2>&1 || true
    update-rc.d "%(ClientBuilder.package_name)" remove >/dev/null 2>&1 || true
  fi
fi

if [ "$1" = "configure" ]; then
  if [ -n "%(Client.unprivileged_group)" ]; then
    # creating unprivileged group if it isn't already there
    if ! getent group "%(Client.unprivileged_group)" >/dev/null; then
      addgroup --system --force-badname --quiet "%(Client.unprivileged_group)"
    fi
    if [ -n "%(Client.unprivileged_user)" ]; then
      # creating unprivileged user if it isn't already there
      if ! getent passwd "%(Client.unprivileged_user)" >/dev/null; then
        adduser --system --force-badname --quiet \
          --ingroup "%(Client.unprivileged_group)" \
          --home /nonexistent --no-create-home \
          --shell /usr/sbin/nologin \
          "%(Client.unprivileged_user)"
      fi
    fi
  fi
fi

#DEBHELPER#
