#!/bin/bash
#  $Id$
#  Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
#
#  Allows access to server config information, without running a server process
#  or "config edit" commands.

ARGS_SINGLE_VALUED=3

change_property ()
{
    # $1=property_file $2=property $3=new_value
    # For multi-valued attributes $4 and upwards may also be set
    propfile="$TTADIR/var/serverconfig/$1"
    prop="$2"
    val="$3"

    if [ $# -gt ${ARGS_SINGLE_VALUED} ]
    then
        # The attribute is multi-valued
        while [ -n "$4" ]
        do
          val="${val},$4"
          shift
        done
    fi

    if [ ! -f "$propfile" ]; then
        echo "$l_missing $propfile"
    else
        sed "s;^\(${prop}=\).*;\1${val};" "$propfile" > "$propfile.$$"
        [ `wc -l <"$propfile"` -eq `wc -l <"$propfile.$$"` ] && cp "$propfile.$$" "$propfile" && rm -f "$propfile.$$" 2>/dev/null
        _privusrgrp=`cat $TTADIR/var/serverconfig/global/array.properties 2>/dev/null | awk -F= \
            'BEGIN { u="ttasys"; g="ttaserv" }
            $1 == "tarantella.config.array.privilegeduser"  { u = $2 }
            $1 == "tarantella.config.array.privilegedgroup" { g = $2 }
            END { print u " " g }'`
        _privusr=`expr "$_privusrgrp" : '\(.*\) .*'`
        _privgrp=`expr "$_privusrgrp" : '.* \(.*\)'`
        chmod 600 "$propfile"; chgrp $_privgrp "$propfile"; chown $_privusr "$propfile"
        echo "Configured $prop to $val"
    fi
}


# handy shortcut vars
TCS="tarantella.config.server"

if [ $# -gt ${ARGS_SINGLE_VALUED} ]
then
    # Attr is multi-valued
    prop_file="$1"
    attr="${TCS}.$2"
    value="$3"
    
    shift; shift; shift
    change_property "${prop_file}" "${attr}" "${value}" $@
else
    # Make the change
    change_property "$1" "${TCS}.$2" "$3"
fi

exit 0
