#!/bin/sh
#
# $Id: run_script,v 1.2 2004/02/23 16:00:15 jg Exp $
#
#
# Project     :  SCPM (System Configuration Profile Management)
# Module      :  SCPM utilities
# File        :  run_script
# Description :  Runs pre/post/start/stop profile scripts
# Author      :  Joachim Gleissner <jg@suse.de>
#
# Copyright 2002-2004 SuSE Linux AG
#
# Released under the terms of the GNU General Public License
# (see file COPYRIGHT in project root directory).
#

test -z "$1" && { echo "No script name given." >&2 ; exit 1 ; }
test "$1" = "-" ||
	test -f "$1" || { echo "No such file $1" >&2 ; exit 1 ; }

TMPDIR=$( mktemp -d /tmp/scpm_script_log.XXXXXX) || {
    echo "Could not create temporary directory" >&2 ; exit 1; }

# tell SCPM where to find the logs
echo "$TMPDIR" >&2

scpm_log()
{
    test -z "$2" && return
    if [ "$1" = "INFO" -o "$1" = "info" ]; then
	logclass="info"
	shift
    elif [ "$1" = "WARNING" -o "$1" = "warning" ]; then
	logclass="warning"
	shift
    elif [ "$1" = "ERROR" -o "$1" = "error" ]; then
	logclass="ERROR"
	shift
    elif [ "$1" = "DEBUG" -o "$1" = "DEBUG" ]; then
	logclass="debug"
	shift
    else
	logclass="INFO"
    fi
    echo "$logclass ($0) $logclass $*" >> $TMPDIR/messages
}


scpm_exit()
{
    exitcode=$1
    test -z "$exitcode" && exitcode=0
    echo $exitcode > $TMPDIR/exitcode
    exit 0
}

scpm_abort()
{
    touch $TMPDIR/aborted
    scpm_exit $1
}

export -f scpm_log
export -f scpm_exit
export -f scpm_abort
export TMPDIR

if [ "$1" = "-" ]; then
    scpm_log DEBUG "reading from stdin, running through /bin/sh"
    /bin/sh - 2>&1 | tee $TMPDIR/output
    retval=$?
elif [ -x "$1" ]; then
    $1 2>&1 | tee $TMPDIR/output
    retval=$?
else
    scpm_log WARNING "$1 has no executable flag, running through /bin/sh"
    /bin/sh $1 2>&1 | tee $TMPDIR/output
    retval=$?
fi

if [ $retval -ne 0 ]; then
    test -f $TMPDIR/exitcode || echo $retval > $TMPDIR/exitcode
fi

test -s $TMPDIR/output || rm -f $TMPDIR/output

exit 0
