#!/bin/sh

SAVED_IFS="$IFS"

filename() {
    IFS="/"
    result=""
    for part in $1; do
        result="$part"
    done
    IFS="$SAVED_IFS"
    echo "$result"
}

dirname() {
    IFS="/"
    prev_part=""
    result=""
    for part in $1; do
        IFS="$SAVED_IFS"
        if [ "$part" == "" ]; then
            part="/"
        fi
        if [ "$prev_part" != "" ]; then
            if [ "$result" == "" ]; then
                result="$prev_part"
            elif [ "$result" == "/" ]; then
                result=/"$prev_part"
            else
                result="$result"/"$prev_part"
            fi
        fi
        prev_part="$part"
    done
    if [ "$result" == "" ]; then
        result="."
    fi
    IFS="$SAVED_IFS"
    echo "$result"
}

node_subpath() {
    IFS="c-sn"
    while read nul cab row case slot mcomp; do
        echo "cab$cab/row$row/case$case/slot$slot/mcomp$mcomp"
    done < /proc/cray_xt/cname
    IFS="$SAVED_IFS"
}

base_log_dir() {
    IFS=" 	=" # space, tab, =
    while read tag value; do
        if [ "$tag" == "log_file" ]; then
            IFS="$SAVED_IFS"
            dirname $value
            return
        fi
    done < /etc/auditd.conf
    IFS="$SAVED_IFS"
}

base_log_name() {
    IFS=" 	=" # space, tab, =
    while read tag value; do
        if [ "$tag" == "log_file" ]; then
            IFS="$SAVED_IFS"
            filename $value
            return
        fi
    done < /etc/auditd.conf
    IFS="$SAVED_IFS"
}

cluster() {
    TRUE=0
    FALSE=1
    IFS=" 	=" # space, tab, =
    while read tag value; do
        if [ "$tag" != "cluster" ]; then
            continue
        fi
        IFS="$SAVED_IFS"
        case "$value" in
            [Yy][Ee][Ss]) return $TRUE ;;
            *)            return $FALSE ;;
        esac
    done < /etc/auditd.conf
    IFS="$SAVED_IFS"
    return $FALSE
}

UPDATE_FILE=/cray/audit/updates/"$SID"
ACK_FILE=$(base_log_dir)/$(node_subpath)/.ack/"$SID"
TMP_FILE=/tmp/auditctl."$SID".$$
if [ ! -d "$UPDATE_FILE" ]; then
    UPDATE_FILE=$(base_log_dir)/.updates/"$SID"
fi

if [ -e "$TMP_FILE" -o -e "$ACK_FILE" ]; then
    # Results already exist or are in progress, don't interfere, this is
    # a retry, and we have already done the job.
    exit 0
fi

if /sbin/auditctl $(cat $UPDATE_FILE) > $TMP_FILE 2>&1; then
    > $ACK_FILE
else
    cat $TMP_FILE > $ACK_FILE
fi
rm -f $TMP_FILE
exit 0
