#!/bin/bash -e

BASEDIR=$(dirname $(readlink -f $0))

CONF="${CONF:-${BASEDIR}/fusion-sys.cfg}"
LOCK="$CONF.lock"

lockfile() {
    local n
    while [ -f "$LOCK" ]; do
        n=$((n+1))
        if [ $n -ge 10 ]; then
            return 1
        fi
        sleep 2
    done
    touch "$LOCK"
}

if [ "$#" -ne 2 ]; then
    echo "usage: ${0##*/} <var> <value>" >&2
    exit 1
fi

var="$1"
value=$(echo "$2" | sed "s/'/'\\\\''/")

if ! echo "$var" | grep -q '^[A-Za-z0-9_]\+$'; then
    echo "ERROR: variables must consist only of English letters, numbers, and underscores" >&2
    exit 1
fi

lockfile "$LOCK"

sed -i "/^$var=/ d" "$CONF" 2>/dev/null || true
printf "%s='%s'\n" "$var" "$value" >>"$CONF"

rm -f "$LOCK"
