#!/bin/bash

ERROR_USAGE=1
ERROR_FILE_NOT_FOUND=2

printUsage()
{
    echo "Usage: trapHost add <IP address> <keys>"
    echo "Usage: trapHost remove <IP address>"
    echo "Usage: trapHost list hosts"
    echo "Usage: trapHost list traps"
}

if [ $# -lt 1 ]; then
    printUsage
    exit $ERROR_USAGE
fi

# Set up the path to the top-level hmc directory
if [ "$CONSOLE_PATH" != "" ]; then
    hmcdir="$CONSOLE_PATH"
elif [ "$HWMCAHOME" != "" ]; then
    hmcdir="$HWMCAHOME"
elif [ -e /opt/ccfw ]; then
    hmcdir="/opt/ccfw"
elif [ -e /console ]; then
    hmcdir="/console"
else
    echo "Unable to find the top-level HMC directory"
    echo "Set the CONSOLE_PATH environment variable to the correct directory"
    exit $ERROR_FILE_NOT_FOUND
fi

hostsfile="$hmcdir/data/snmp.traps.properties"
trapsfile="$hmcdir/data/snmp.trapsconfig.properties"
classpath=$hmcdir

# Try to add the ccfw.jar to the classpath
if [ -e ccfw.jar ]; then
    classpath="$classpath:ccfw.jar"
elif [ -e "$hmcdir/ccfw.jar" ]; then
    classpath="$classpath:$hmcdir/ccfw.jar"
fi
classpath="$classpath:."

# Find the java executable
if which java >/dev/null 2>&1; then
    javabin="java"
elif [ "$JAVA_HOME" != "" ]; then
    javabin="$JAVA_HOME/bin/java"
else
    echo "java executable not found"
    exit 1
fi


# Parse the arguments
op=$1

if [ "$op" = "add" ]; then
    if [ $# -ne 3 ]; then
        printUsage
        exit $ERROR_USAGE
    fi

    addr=$2
    keys=$3
    $javabin -cp $classpath com.ibm.hwmca.base.settings.snmp.SnmpCommandLine addTrapHost $hmcdir $addr $keys
    exit $?
elif [ "$op" = "remove" ]; then
    if [ $# -ne 2 ]; then
        printUsage
        exit $ERROR_USAGE
    fi

    addr=$2
    $javabin -cp $classpath com.ibm.hwmca.base.settings.snmp.SnmpCommandLine removeTrapHost $hmcdir $addr
    exit $?
elif [ "$op" = "list" ]; then
    if [ "$2" = "traps" ]; then
        echo "Key: Description"
        echo "----------------"
        grep "=" $trapsfile | sed -e "s/=/: /"
        exit 0
    elif [ "$2" = "hosts" ]; then
        echo "IP Address: Trap keys"
        echo "---------------------"
        grep "=" $hostsfile | sed -e "s/=/: /"
        exit 0
    else
        printUsage
        exit $ERROR_USAGE
    fi
else
    printUsage
    exit $ERROR_USAGE
fi

