# BEGIN smf/preremove
#
# Copyright 2006 Yann Rouillard <yann@pleiades.fr.eu.org>
# All rights reserved.  Use is subject to license terms.
#
# Redistribution and/or use, with or without modification, is
# permitted.  This code is without warranty of any kind.  The
# author(s) shall not be liable in the event that use of the
# software causes damage.
#
# preremove script which save the current state of 
# services (enabled/disabled/...)
#

# returns the list of frmi defined in a given manifest file
get_fmri_list ()
{
    chroot "$PKG_INSTALL_ROOT" /usr/sbin/svccfg inventory "$1" | awk -F: ' NF > 2 { print $0 }'
}

# returns the current state of the service for smf based launch scripts
read_smf_service_state ()
{
    PERMANENT_STATE=`/usr/sbin/svccfg -s "$1" listprop general/enabled | /usr/bin/awk '{ print $3 }'`
    if [ "$PERMANENT_STATE" != "true" ]; then
        PERMANENT_STATE="disabled"
    else
        PERMANENT_STATE="enabled"
    fi

#    TEMPORARY_STATE=`/usr/sbin/svccfg -s "$1" listprop general_ovr/enabled | /usr/bin/awk '{ print $3 }'`
#    if [ "$TEMPORARY_STATE" != "true" ]; then
#        TEMPORARY_STATE="disabled"
#    else
#        TEMPORARY_STATE="enabled"
#    fi
}

read_conf_value () 
{
    _VAR="$1"
    _FILE="$2"
    eval ${_VAR}=\"`/usr/bin/sed -n -e "/^# *$_VAR:/ s/^.*$_VAR: *\(.*[^ ]\) *$/\1/p" ${_FILE}`\"
}

# save the service state in the state file
save_service_state ()
{
    echo "$1 $PERMANENT_STATE" >> "$STATE_FILE"
}



if [ -z "$PKG_INSTALL_ROOT" ]; then 
    PKG_INSTALL_ROOT=/
fi

STATE_FILE="$PKG_INSTALL_ROOT/var/tmp/$PKG.smfinfo" 
rm -f "$STATE_FILE"

# is SMF available ?
if [ -f "$PKG_INSTALL_ROOT/usr/sbin/svccfg" -a -f "$PKG_INSTALL_ROOT/usr/sbin/svcadm" ]; then

    for FILE in $MANIFEST_FILES; do
        for FMRI in `get_fmri_list "$FILE"`; do
            read_smf_service_state "$FMRI"
            save_service_state "$FMRI"
            /usr/sbin/chroot "$PKG_INSTALL_ROOT" /usr/sbin/svcadm disable -s "$FMRI"
        done
    done

else
    # with init scripts, we don't save/restore the state
    # This behaviour was refused by Phil Brown
    for FILE in $INIT_FILES; do
        /usr/sbin/chroot "$PKG_INSTALL_ROOT" "$FILE" stop
    done

fi

true
# END smf/preremove
