#!/bin/bash # TODO: Add a 'get' method that returns a single value # Exit with 0 if found, 1 otherwise. key_expr="[a-zA-Z][_a-zA-Z0-9]*\.[a-zA-Z][_a-zA-Z0-9]*" format_conf() { local IFS== while read key value do printf "%-20s %-20s" "$key" "$value" echo done } get_conf() { local apps=$1 local name=$2 local instance=$3 local key=$4 local default= local file=$apps/$name/$instance/current/etc/app.conf shift 4 if [ $# -gt 0 ] then default=$1 shift fi if [ ! -r $file ] then echo "$default" return 0 fi value=`sed -n "s,^${key}[ ]*=[ ]*\(.*\)$,\1,p" $file` if [ -z "$value" ] then echo "$default" fi echo "$value" } get_conf_all() { local apps=$1 local name=$2 local instance=$3 local file=$apps/$name/$instance/current/etc/app.conf if [ ! -r "$file" ] then return 0 fi sed -n "s,^[ ]*\($key_expr\)[ ]*=[ ]*\(.*\)$,\1=\2,p" "$file" | sort } get_conf_in_group() { local apps=$1 local name=$2 local instance=$3 local group=$4 get_conf_all "$apps" "$name" "$instance" | sed -n "s,^${group}\.\(.*\),\1,p" } assert_key() { key=$1 local x=`echo $key | sed -n "/^$key_expr$/p"` if [ -z "$x" ] then echo "Invalid key: $key" >&2 exit 1 fi } conf_set() { local apps=$1 local name=$2 local instance=$3 local key=$4 local value=$5 local file=$apps/$name/$instance/current/etc/app.conf assert_key "$key" if [ -r $file ] then sed "/^$key[ ]*=.*/d" $file > $file.tmp fi echo "$key=$value" >> $file.tmp mv $file.tmp $file } conf_delete() { local apps=$1 local name=$2 local instance=$3 local key=$4 local file=$apps/$name/$instance/current/etc/app.conf assert_key "$key" sed "/^$key[ ]*=.*/d" $file > $file.tmp mv $file.tmp $file } method_conf_list() { local name=$1; shift local instance=$1; shift get_conf_all "$apps" "$name" "$instance" | format_conf } method_conf_usage() { if [ -n "$1" ] then echo "Error:" $@ >&2 fi echo "usage: $0 conf " >&2 echo "" echo "Available methods:" >&2 echo " list - list all configuration values" >&2 echo " list-group [group] - list all configuration values in the specified group" >&2 echo " set [group.key] [value] - set a configuration parameter" >&2 echo " delete [group.key] - deletes a configuration parameter" >&2 exit 1 } method_conf() { local name="$1"; shift local instance="$1"; shift local method="$1" if [ $# -gt 0 ] then shift fi assert_is_instance method_conf_usage "$name" "$instance" case "$method" in list) if [ $# -gt 0 ] then method_conf_usage "Extra options." exit 1 fi method_conf_list "$name" "$instance" ;; list-group) if [ $# -ne 1 ] then method_conf_usage exit 1 fi get_conf_in_group "$apps" "$name" "$instance" "$1" | format_conf ;; set) if [ $# -ne 2 ] then method_conf_usage exit 1 fi conf_set "$apps" "$name" "$instance" "$1" "$2" ;; delete) if [ $# -ne 1 ] then method_conf_usage exit 1 fi conf_delete "$apps" "$name" "$instance" "$1" ;; *) if [ $# -eq 0 ] then method_conf_list "$name" "$instance" exit 0 fi if [ -z "$method" ] then method_conf_usage else method_conf_usage "Unknown method $method" fi exit 1 ;; esac }