#!/bin/bash

set -e
set -u

APPSH_HOME=$(cd $(dirname "$0")/.. && pwd)

. $APPSH_HOME/lib/common
# HEADER END

# TODO: Add a 'get' command that returns a single value
# If -r (required) given, exit with 0 if found, 1 otherwise.
# TODO: Add -s (shell) output, `app-conf get -s maven.artifact_id` => MAVEN_ARTIFACT_ID=..
# Can be used like set -- `app-conf get -s maven.artifact_id maven.group_id`

PATH=$APPSH_HOME/libexec:$PATH

key_expr="[a-zA-Z][_a-zA-Z0-9]*"

format_conf() {
  local IFS==
  while read key value
  do
    printf "%-20s %-20s" "$key" "$value"
    echo
  done
}

assert_valid_config_name() {
  local name=$1

  local x=`echo $name | sed -n "/^$key_expr\\.$key_expr$/p"`
  if [ -z "$x" ]
  then
    echo "Invalid name: $name" >&2
    exit 1
  fi
}

conf_set() {
  local name=$1; shift
  local value=$1; shift

  assert_valid_config_name "$name"

  if [ -r $file ]
  then
    sed "/^$name[ ]*=.*/d" $file > $file.tmp
  fi

  echo "$name=$value" >> $file.tmp
  mv $file.tmp $file
}

conf_delete() {
  local name=$1; shift

  assert_valid_config_name "$name"

  sed "/^$name[ ]*=.*/d" $file > $file.tmp
  mv $file.tmp $file
}

usage() {
  if [ -n "$1" ]
  then
    echo "Error: $@" >&2
  fi

  echo "usage: $0 conf <command>" >&2
  echo ""
  echo "Available commands:" >&2
  echo "  list               - list all config values" >&2
  echo "  set [name] [value] - set a config parameter" >&2
  echo "  delete [name]      - deletes a config parameter" >&2
  exit 1
}

if [ $# -gt 0 ]
then
  command=$1
  shift
else
  command=list
fi

file=".app/config"

assert_is_app -C

case "$command" in
  get)
    if [ $# != 1 ]
    then
      usage
      exit 1
    fi

    app-cat-conf -f "$file" -n "$1" | cut -f 2 -d = | format_conf | sed "s, *$,,"
    ;;
  list)
    if [ $# -gt 0 ]
    then
      usage "Extra options."
      exit 1
    fi

    app-cat-conf -f "$file" | format_conf
    ;;
  set)
    if [ $# -ne 2 ]
    then
      usage
      exit 1
    fi

    conf_set "$1" "$2"
    ;;
  delete)
    if [ $# -ne 1 ]
    then
      usage "Missing [name] argument."
      exit 1
    fi

    conf_delete "$1"
    ;;
  *)
    if [ -z "$command" ]
    then
      usage
    else
      usage "Unknown command: $command"
    fi
    exit 1
    ;;
esac