#!/bin/bash

set -e
set -u

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

. $APPSH_HOME/lib/common
# HEADER END

files=()
arg_files=()
declare -a arg_files
use_default_files=yes

location=app
mode=all

while getopts "f:Dk:g:l:" opt
do
  case $opt in
    f)
      file="$OPTARG"
      if [[ $file == "-" ]]
      then
        file=/dev/stdin
      fi
      arg_files+=($file)
      ;;
    D)
      use_default_files=no
      ;;
    k)
      key=$OPTARG
      mode=key
      if [[ ! $key =~ $key_expr\.$key_expr ]]
      then
        echo Invalid key name: $key
        exit 1
      fi
      ;;
    g)
      group=$OPTARG
      mode=group
      if [[ ! $group =~ $key_expr ]]
      then
        echo Invalid group name: $group
        exit 1
      fi
      ;;
    l)
      location=$OPTARG
      ;;
    *)
      usage "Invalid option: $opt"
      ;;
  esac
done

shift $(($OPTIND - 1))

if [[ $# != 0 ]]
then
  usage "extra arguments"
fi

validate_location location

if [[ $use_default_files == yes ]]
then
  _get_config_file_system config_s
  _get_config_file_user config_u
  _get_config_file_app config_a

  files+=($config_s)

  if [ "$location" -ge 2 -a -r "$config_u" ]
  then
    files+=("$config_u")
  fi

  if [ "$location" -ge 3 -a -r "$config_a" ]
  then
    files+=("$config_a")
  fi
fi

# Even if arg_files is declared above, the files+= statement will fail
# with "unbound" variable. bash-4.2.45.
if [ "${#arg_files[@]}" -gt 0 ]
then
  files+=("${arg_files[@]}")
fi

case $mode in
  all)
    filter="$key_expr\.$key_expr"
    ;;
  group)
    filter="$group\.$key_expr"
    ;;
  key)
    filter=$key
    ;;
esac

filter="s,^[ ]*\($filter\)[ ]*=[ ]*\(.*\)$,\1=\2,p"

debug "Using files:" "${files[@]}"

(for ((idx=${#files[@]}-1 ; idx>=0 ; idx-- )); do cat ${files[idx]}; done) | \
  sed -n -e "$filter" | \
  awk -F = ' (!($1 in a)){a[$1]; print }' | \
  sort