#!/bin/bash

set -e
set -u

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

. $APPSH_HOME/lib/common
# HEADER END

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

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

location=app

while getopts "f:Dn:l:" opt
do
  case $opt in
    f)
      file="$OPTARG"
      if [[ $file == "-" ]]
      then
        file=/dev/stdin
      fi
      arg_files+=($file)
      ;;
    D)
      use_default_files=no
      ;;
    n)
      name=$OPTARG
      ;;
    l)
      location=$OPTARG
      ;;
    \?)
      usage "Invalid option: $opt"
      ;;
  esac
done

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

# TODO: find config files in the paths above $file's paths and perhaps
# /etc/appsh/config.

if [ -z "$name" ]
then
  filter="s,^[ ]*\($key_expr\.$key_expr\)[ ]*=[ ]*\(.*\)$,\1=\2,p"
else
  filter="s,^\($name\)=\(.*\),\1=\2,p"
fi

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

# The awk script makes sure each key only appears once. The first one wins

(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