#!/bin/sh
#
# Copyright (C) 2012-2013 Red Hat, Inc.  All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
# Authors: Radek Novacek <rnovacek@redhat.com>
#

pegasus_repository="/var/lib/Pegasus/"
default_namespace="root/cimv2"

function start_pegasus()
{
    # Start Pegasus CIMOM in restricted mode, listening only on its unix socket
    /usr/sbin/cimserver daemon=true \
            enableHttpConnection=false \
            enableHttpsConnection=false \
            enableRemotePrivilegedUserAccess=false \
            slp=false

    if [ "$?" != "0" ]; then
        echo "Cannot start Pegasus" >&2
        exit 1
    fi
}

function stop_pegasus()
{
    /usr/sbin/cimserver -s
}

function usage()
{
    printf "Usage: $0 [ --just-mofs ] [ -n namespace ] [ -c cimom ]
                    CMD <mof> [mof] [...] [reg]
    CMD is one of [ register, unregister ]

    Default namespace is $default_namespace, which can be changed with '-n' option.

    Supported cimoms are sfcbd and tog-pegasus. Without \"-c\" argument, the
    operation is processed for any cimom present on system (all of them).

    --just-mofs option causes that all arguments after CMD will be
      treated as mof files - no registration file is expected.

      usage with --just-mofs:
        $0 CMD <mof> [mof] [...]
      usage without:
        $0 CMD <mof> [mof] [...] <reg>\n"
 
}

function register()
{
    if [ $JUST_MOFS -eq 0 ]; then
        reg=$1
        shift
    fi
    mofs="$@"
    if [ $HAS_SFCBD -eq 1 ] && echo $cimom | grep -q 'all\|sfcbd';
    then
        /usr/bin/sfcbstage -n $namespace ${reg:+-r} $reg $mofs
        /usr/bin/sfcbrepos -f
        /usr/bin/systemctl reload-or-try-restart sblim-sfcb.service
    fi

    if [ $HAS_PEGASUS -eq  1 ] && echo $cimom | grep -q 'all\|tog-pegasus';
    then
        /usr/sbin/cimserver --status > /dev/null 2>&1
        if [ $? -eq 0 ];
        then
            CIMMOF="/usr/bin/cimmof -aEV -n $namespace"
        else
            CIMMOF="/usr/bin/cimmofl -aEV -R $pegasus_repository -n $namespace"
        fi

        $CIMMOF -uc $mofs
        if [ $JUST_MOFS -eq 0 ]; then
            if [ -x $(dirname $0)/openlmi-register-pegasus ];
            then
                cat "$reg" | $(dirname $0)/openlmi-register-pegasus | $CIMMOF -uc -n root/PG_Interop
            else
                cat "$reg" | /usr/libexec/openlmi-register-pegasus | $CIMMOF -uc -n root/PG_Interop
            fi
        fi
    fi
}

function unregister()
{
    if [ $JUST_MOFS -eq 0 ]; then
        reg=$1
        shift
    fi

    declare -a mofs=("$@")
    if [ $HAS_SFCBD -eq 1 ] && echo $cimom | grep -q 'all\|sfcbd';
    then
        # convert mofs to `basename mof`
        declare -a bmofs
        for ((i=0; i<${#mofs[@]}; i++)); do
            bmofs[$i]=$(basename "${mofs[$i]}")
        done
        /usr/bin/sfcbunstage -n $namespace ${reg:+-r} $(basename "$reg") ${bmofs[@]}
        /usr/bin/sfcbrepos -f
        /usr/bin/systemctl reload-or-try-restart sblim-sfcb.service
    fi

    if [ $HAS_PEGASUS -eq 1 ] && echo $cimom | grep -q 'all\|tog-pegasus';
    then
        # Pegasus must be running when removing MOF files and providers
        if ! /usr/sbin/cimserver --status &>/dev/null; then
            CUSTOM_PEGASUS=1
            start_pegasus
        fi
        if [ -n "$reg" ];
        then
            for provider in $(sed -n 's/ *group: *//p' "$reg" | sort | uniq);
            do
                /usr/bin/cimprovider -d -m ${provider} && /usr/bin/cimprovider -r -m ${provider}
            done
        fi
        mofcomp -n $namespace -r ${mofs[@]}
        if [ -n "$CUSTOM_PEGASUS" ]; then
            stop_pegasus
        fi
    fi
}

JUST_MOFS=0
optspec=":hn:c:-:"

while getopts "$optspec" optchar; do
    case "$optchar" in
        -)  # long options parsing
            case "$OPTARG" in
                just-mofs)
                    JUST_MOFS=1
                    ;;
                help)
                    usage;
                    exit 0;
                    ;;
                *)
                    if [ "$OPTERR" != 1 ] || [ "${optspec:0:1}" = ":" ]; then
                        echo "Unknown option --${OPTARG}" >&2
                        exit 1
                    fi
                    ;;
            esac
            ;;
        n)
            namespace="$OPTARG"
            ;;
        c)
            cimom="$OPTARG"
            if [ "$cimom" != "sfcbd" -a "$cimom" != "tog-pegasus" ]; then
                echo "Not supported cimom: $cimom" >&2
                exit 1
            fi
            ;;
        h)
            usage;
            exit 0;
            ;;
        *)
            if [ "$OPTERR" != 1 ] || [ "${optspec:0:1}" = ":" ]; then
                echo "Non-option argument: '-${OPTARG}'" >&2
                exit 1
            fi
            ;;
    esac
done

shift $(($OPTIND - 1))
namespace=${namespace:-$default_namespace}
cimom=${cimom:-all}

if [ $# -lt 2 ];
then
    usage
    exit 1
fi

if [ -e /usr/sbin/sfcbd ];
then
    HAS_SFCBD=1
else
    HAS_SFCBD=0
    if [ $cimom = "sfcbd" ]; then
        echo "Sfcbd not detected on system!" >&2
        exit 1
    fi
fi

if [ -e /usr/sbin/cimserver ];
then
    HAS_PEGASUS=1
else
    HAS_PEGASUS=0
    if [ $cimom = "tog-pegasus" ]; then
        echo "Pegasus not detected on system!" >&2
        exit 1
    fi
fi

# TODO: check if at least one server is installed
CMD=$1
shift

# parse the reg and mofs - use $@ and remove the last item
declare -a ARGS=("$@")
if [ $JUST_MOFS -eq 0 ];
then
    LEN=$(( ${#ARGS[@]} -1 ))
    REG=${ARGS[$LEN]}
    MOFS=(${ARGS[@]:0:$(($LEN))})
else
    MOFS=("$@")
fi

case $CMD in
    register)
        register $REG ${MOFS[@]}
        ;;
    unregister)
        unregister $REG ${MOFS[@]}
        ;;
    **)
        usage
        exit 1
esac
