#!/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
}

conf_import() {
  local dst=$1; shift
  local src=$1; shift

  echo "Importing config from $src"
  app-cat-conf -f "$src" -f "$dst" > "$dst.tmp"
  mv "$dst.tmp" "$dst" 
}

usage_text() {
  echo "usage: $0 conf <command>"
  echo ""
  echo "Available commands:"
  echo "  get [name]         - returns a single value"
  echo "  list               - list all config values"
  echo "  set [name] [value] - set a config parameter"
  echo "  delete [name]      - deletes a config parameter"
  echo "  import [file]      - import a file"
  exit 1
}

app_home=${APP_HOME-.}
file="$app_home/.app/config"

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

assert_is_app -C

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

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

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

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

    conf_delete "$1"
    ;;
  import)
    if [ $# -ne 1 ]
    then
      usage "Missing [file] argument."
      exit 1
    fi

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