#!/bin/sh

##
## Add or remove entries in /etc/sudoers
## This script is intended to be used as an editor by the visudo command
## and is called during the install/uninstall of hp-smh-templates.
##
## Add vs. remove mode is determined by the name of the command used ($0)
##

set -e

if [ $# -ne 1 ]; then
    # we only expect visudo to pass us a single filename,
    # so bail if that's not the case
    exit 1
fi

SNMPD="%hpsmh ALL=NOPASSWD:/etc/init.d/snmpd"
SNMPTRAP="%hpsmh ALL=NOPASSWD:/usr/bin/snmptrap"
BEGINMARKER="# The following entries were added by hp-smh-templates at"
ENDMARKER="# ---------------------- END --------------------"
tmpfile="$1"

if [ "$(basename $0)" = "del-sudo-entries" ]; then
  sed -i "/${BEGINMARKER}/,/${ENDMARKER}/d" "$tmpfile"
  exit 0
fi

need_snmpd=1
if grep -q "$SNMPD" "$tmpfile"; then
    need_snmpd=0
fi

need_snmptrap=1
if grep -q "$SNMPTRAP" "$tmpfile"; then
    need_snmptrap=0
fi

if [ $need_snmpd -eq 0 -a $need_snmptrap -eq 0 ]; then
    exit 0
fi

printf "${BEGINMARKER}\n" >> "$tmpfile"
printf "#      " >> "$tmpfile"
date >> "$tmpfile"
printf "# WARNING! Any changes between here and the END marker are managed by hp-health\n" >> "$tmpfile"
printf "# and maybe automatically removed.\n" >> "$tmpfile"

if [ $need_snmpd -eq 1 ]; then
    SNMPD="$(echo "$SNMPD" | sed 's/%/%%/')"
    printf "${SNMPD}\n" >> "$tmpfile"
fi
if [ $need_snmptrap -eq 1 ]; then
    SNMPTRAP="$(echo "$SNMPTRAP" | sed 's/%/%%/')"
    printf "${SNMPTRAP}\n" >> "$tmpfile"
fi
printf "${ENDMARKER}\n" >> "$tmpfile"
