#!/bin/bash

#set -x

# Default values
infile="prepare_dir.json"
keyboard="US"
pljava="FALSE"
def_p2j_entry="login.p"
def_propath=".:"
def_search_path=".:"
defdbname="hotel"
backup=false
overwrite=false
srvcerts_store="srvcerts.store"
# Environment is used for Docker containers
[ -z "$ADMIN_CONSOLE_PASSWORD" ]  && admin_console_pw="test123" || admin_console_pw=$ADMIN_CONSOLE_PASSWORD
[ -z "$APP_DBADMIN_PASSWORD" ] && db_admin_pw="admin" || db_admin_pw=$APP_DBADMIN_PASSWORD
[ -z "$APP_DBUSER_PASSWORD" ]  && db_user_pw="user"   || db_user_pw=$APP_DBUSER_PASSWORD
[ -z "$ROOT_CA_PASSWORD" ]    && root_ca_pw="password"   || root_ca_pw=$ROOT_CA_PASSWORD
[ -z "$SRV_CERTS_PASSWORD" ]  && srv_certs_pw="password" || srv_certs_pw=$SRV_CERTS_PASSWORD

show_usage()
{
   cat <<EOF
Usage: $0 [-o]] [--admin_pw=<password>] [--db_admin_pw=<password>] [--db_user_pw=<password>] [--root_ca_pw=<password>] [--srv_certs_pw=<password>] [--backup] [-f <json_cfg_file>"]
Where:
   o = Overwrite the specified directory.xml, otherwise fail
   --admin_pw=<password> Password to use for the Admin Console (def=${admin_console_pw}).
   --db_admin_pw=<password> Password to use for \"fwd_admin\" (def=${db_admin_pw}).
   --db_user_pw=<password> Password to use for \"fwd_user\" (def=${db_user_pw}).
   --root_ca_pw=<password> Password to use for Root CA (def=[${root_ca_pw}]).
   --srv_certs_pw=<password> Password to use for \"${srvcerts_store}\" (def=${srv_certs_pw}).
   --backup Make a backup of the directory as \"directory.xml.backup\"
   f = input from [json_cfg_file] (def=\"${infile}\". To use the default, make sure this is the last parameter.)
EOF
}

# This has limited potential. It has 2 limits:
# 1) We can only have 1 argument with options
# 2) It must be at the end of the list of arguments
# Other than that, it works great.
getopts_get_optional_argument()
{
  eval next_token=\${$OPTIND}
  #${parameter:offset:length}
  if [[ "${next_token:0:1}" = "-" ]]; then
     next_token=${next_token:2}
  fi
  if [[ -n $next_token && $next_token != -* ]]; then
    OPTIND=$((OPTIND + 1))
    OPTARG=$next_token
  else
    OPTARG=""
  fi
}

# Use this in case there are characters in the string that might be the sed delimiter
# call:  escaped_hash=$(escape_sed_replacement "$admin_console_pw_hash")
# usage in sed: sed "s|{admin_console_pw}|$escaped_hash|g" template.txt
escape_sed_replacement()
{
   printf '%s' "$1" | sed -e 's/[&/\]/\\&/g'
}
# Use this in case there are characters in the string that need to be replaced so they
# can be used in XML. These would be:
# '&' -> &amp; '<' -> &lt; '>' -> &gt; '"' -> &quot; ''' -> &apos;
xml_escape()
{
   local s=$1

   s=${s//&/\&amp;}
   s=${s//</\&lt;}
   s=${s//>/\&gt;}
   s=${s//\"/\&quot;}
   s=${s//\'/\&apos;}

   printf '%s' "$s"
}

# Retrieve a subkey under the main group from the JSON. Allow default to be passed
function sub_getval()
{
   local parent="$1"   # e.g. broker1
   local key="$2"
   local default="$3"
   local file="$4"

   if val=$(_sub_getval "$parent" "$key" "$file"); then
      printf '%s\n' "$val"
   else
      printf '%s\n' "$default"
   fi
}
# Retrieve a subkey under the main group from the JSON.
function _sub_getval()
{
   local parent="$1"   # e.g. broker1
   local key="$2"      # e.g. client_xml_file
   local file="$3"
   local val

   if [[ -z "$parent" || -z "$key" || -z "$file" ]]; then
      echo "get_json_subkey: missing arguments" >&2
      return 1
   fi

   if ! val=$(jq -er --arg p "$parent" --arg k "$key" \
      '.[$p][$k]' "$file" 2>/dev/null); then
      return 2   # missing key or invalid
   fi

   printf '%s\n' "$val"
}

# Retrieve a key from the JSON. Allow default to be passed
function getval()
{
   local key="$1"
   local default="$2"
   local file="$3"

   if val=$(_getval "$key" "$file"); then
      printf '%s\n' "$val"
   else
      printf '%s\n' "$default"
   fi
}
# Retrieve a key from the JSON.
function _getval()
{
   local key="$1"
   local file="$2"
   local val

   if ! val=$(jq -er ".$key" "$file" 2>/dev/null); then
      return 2   # missing or jq error
   fi

   if [[ "$val" == "null" ]]; then
      return 3   # explicit null
   fi

   printf '%s\n' "$val"
   return 0
}

# Function to load list in JSON into array. Backward compatible with old string keys
# Returns: 0 - all good, even empty array if not required
#          1 - Fail, since array is empty and required
function load_array_from_json()
{
   local key="$1"                # e.g. "dbnames" or "parent.child.list"
   local file="$2"
   local -n out_array="$3"       # nameref target
   local required="${4:-true}"   # true = must exist and non-empty

   # Verify key exists
   if ! jq -e "getpath([\"${key//./\",\"}\"])" "$file" >/dev/null 2>&1; then
      if [[ "$required" == "true" ]]; then
         echo "ERROR: Required key missing: $key" >&2
         return 1
      else
         out_array=()
         return 0
      fi
   fi

   local type
   type=$(jq -r "getpath([\"${key//./\",\"}\"]) | type" "$file")

   case "$type" in
      array )
         mapfile -t out_array < <(
             jq -r "getpath([\"${key//./\",\"}\"])[]" "$file"
         )
         ;;
      string )
         local raw
         raw=$(jq -r "getpath([\"${key//./\",\"}\"])" "$file")
         IFS=',' read -r -a out_array <<< "$raw"
         ;;
      null )
         if [[ "$required" == "true" ]]; then
            echo "ERROR: Required key is null: $key" >&2
            return 1
         else
            out_array=()
            return 0
         fi
         ;;
      * )
         echo "ERROR: $key must be string or array (got $type)" >&2
         return 1
         ;;
   esac

   # Enforce non-empty if required
   if [[ "$required" == "true" ]] && ((${#out_array[@]} == 0)); then
      echo "ERROR: Required key is empty: $key" >&2
      return 1
   fi

   return 0
}

# Helper to perform XML directory copying
directory_copy()
{    
   local srcfile="$1"
   local srclocation="$2"
   local dstfile="$3"
   local dstlocation="$4"

   result=$(java -Xmx256m -classpath $p2j_jar com.goldencode.p2j.directory.DirectoryCopy copy $srcfile $srclocation $dstfile $dstlocation)
   if [ ."$result". != ".." ]; then
      echo "ERROR: ${result}. DirectoryCopy srcfile=$srcfile, srclocation=$srclocation, dstfile=$dstfile, dstlocation=$dstlocation"
      exit 1
   fi
}

hash_password()
{
   local pw="$1"

   hashed=$(java -classpath $p2j_jar com.goldencode.p2j.security.HashPassword $pw)
   if [ ."$hashed". != ".." ]; then
      echo $hashed
   fi
}

# Makes key=value substitutions in the content passed in
render_memory()
{
   local content="$1"
   shift
   local key value kv

   for kv in "$@"; do
      key="${kv%%=*}"
      value="${kv#*=}"
      content="${content//\{$key\}/$value}"
   done

   printf "%s" "$content"
}

# process options
while getopts "h?of-:" opt; do
   case $opt in
      o ) overwrite=true ;;
      f ) getopts_get_optional_argument $@
          infile=${OPTARG:-$infile}
          ;;
      -  ) case ${OPTARG} in
              "admin_pw"*    ) admin_console_pw=$(echo $OPTARG | cut -d"=" -f2) ;;
              "db_admin_pw"* ) db_admin_pw=$(echo $OPTARG | cut -d"=" -f2) ;;
              "db_user_pw"*  ) db_user_pw=$(echo $OPTARG | cut -d"=" -f2) ;;
              "root_ca_pw"*  ) root_ca_pw=$(echo $OPTARG | cut -d"=" -f2) ;;
              "srv_certs_pw"*  ) srv_certs_pw=$(echo $OPTARG | cut -d"=" -f2) ;;
              "backup"       ) backup=true ;;
              * ) echo "Unknown option: --${OPTARG}"
                  show_usage
                  exit 1 ;;
           esac
           ;;
      h | \
      \? ) show_usage && exit 1
           ;;
   esac
done
shift $(($OPTIND - 1))

if [ ! -f "$infile" ]; then
   echo "ERROR: Input file ${infile} not found."
   show_usage && exit 1
fi

# Setup p2j_jar for use in DirectoryCopy
fwd_lib=${FWD_LIB:-"../../p2j"}
if [ ! -e "$fwd_lib" ]; then
   echo "ERROR: Either FWD_LIB must be set to a valid directory or ../../p2j directory must exist so as to locate p2j.jar"
   exit 1
fi
p2j_jar=$([ -e "${fwd_lib}/build/lib/p2j.jar" ] && echo ${fwd_lib}/build/lib/p2j.jar || echo ${fwd_lib}/lib/p2j.jar)
p2j_jar=$([ -e "$p2j_jar" ] && echo $p2j_jar || echo ../../p2j/lib/p2j.jar)

spawner_path=$(getval "spawner_path" "/opt/spawner/spawn" $infile)
server_xml_file=$(getval "server_xml_file" "server.xml" $infile)
directory_xml_file=$(getval "directory_xml_file" "directory.xml" $infile)
client_start_dir=$(getval "client_start_dir" "./deploy/client" $infile)
dateFormat=$(getval "dateFormat" "mdy" $infile)
numberGroupSep=$(getval "numberGroupSep" "," $infile)
numberDecimalSep=$(getval "numberDecimalSep" "." $infile)
p2j_entry=$(getval "p2j_entry" "$def_p2j_entry" $infile)
pkgroot=$(getval "pkgroot" "com.goldencode.hotel" $infile)
propath=$(getval "propath" "$def_propath" $infile)
searchpath=$(getval "search_path" "$def_search_path" $infile)
path_separator=$(getval "path_separator" ":" $infile)
file_separator=$(getval "file_separator" "/" $infile)
case_sensitive=$(getval "case_sensitive" "TRUE" $infile)
user=$(getval "os_user" "$(whoami)" $infile)
keyboard=$(getval "kbd_layout" "US" $infile)
dbuser=$(getval "dbuser" "fwd_user" $infile)
dbuserpass=$(getval "dbuserpass" $db_user_pw $infile)
dbadmin=$(getval "dbadmin" "fwd_admin" $infile)
dbadminpass=$(getval "dbadminpass" $db_admin_pw $infile)
server_log=$(getval "server_log" "../logs" $infile)
client_log=$(getval "client_log" "../logs" $infile)
embedded_host=$(getval "embedded_host" "localhost" $infile)
admin_port=$(getval "admin_port" "7443" $infile)
log_rotation_limit=$(getval "log_rotation_limit" "50000000" $infile)
log_rotation_count=$(getval "log_rotation_count" "4" $infile)
client_lib_path=$(getval "client_lib_path" "../lib" $infile)
webclient_appcds_archive=$(getval "webclient_appcds_archive" "../appcds/client/default.jsa" $infile)
webclient_appcds_template=$(getval "webclient_appcds_jvmargs" "-Xshare:auto -XX:SharedArchiveFile={archive}" $infile)
if [[ "${webclient_appcds_template,,}" != "none" ]]; then
   webclient_appcds_jvmargs=$(render_memory "$webclient_appcds_template" "archive=$webclient_appcds_archive")
   libpath='          <node class="string" name="libPath"> \
            <node-attribute name="value" value="{client_lib_path}"/> \
          </node>'
   libpath_rendered=$(render_memory "$libpath" "client_lib_path=$client_lib_path")
else
   webclient_appcds_jvmargs=""
   libpath_rendered=""
fi
webclient_memory=$(getval "webclient_memory" "1024m" $infile)


# Handle DB load. No entry implies H2 hotel DB.
if ! load_array_from_json "dbnames" "$infile" db_array false \
     || ((${#db_array[@]} == 0)); then
   db_array=("$defdbname")
fi
# Default DB is first in the list (whether 1 or more)
defdatabase=${db_array[0]}

# Determine if we can now create the directory file
if [[ -f "$directory_xml_file" ]]; then
   dirfile=$(realpath -e "$directory_xml_file")
else
   dirfile=$(realpath -e $(dirname $directory_xml_file))/$(basename $directory_xml_file)
fi
if [ -e "$dirfile" ] && [ "$overwrite" == false ]; then
   echo "ERROR: Output file ${dirfile} exists, and '-o' not specified."
   show_usage && exit 9
elif [ -e "$dirfile" ] && [ "$backup" == "true" ]; then
   backup_file=$dirfile
   backup_file+=".backup"
   cp "$dirfile" "$backup_file"
fi
if [ ! -w "$(dirname $dirfile)" ] || ([ -f "$dirfile" ] && [ ! -w "$dirfile" ]); then
   if [ "$USER" != "root" ]; then
      mysudo=sudo
   fi
fi

# Setup the server.xml and directory.xml (if possible).
sed \
    -e "s#{directory_xml_file}#$directory_xml_file#g" \
    server.xml.template > $server_xml_file
rc=$?
if [ $rc -ne 0 ]; then
   echo "ERROR: Could not create $server_xml_file rc=$rc"
   exit $rc
fi

# Hash the admin console password
admin_console_pw_hash=$(hash_password $admin_console_pw)
if [ ."$admin_console_pw_hash". == ".." ]; then
   echo "ERROR: Could not hash admin console password."
   exit 1
fi
escaped_hash=$(escape_sed_replacement "$admin_console_pw_hash")

sed_file_separator=$(echo $file_separator | sed -e 's/\\/\\\\/g')
sed \
    -e "s#{spawner_path}#$spawner_path#g" \
    -e "s#{client_start_dir}#$client_start_dir#g" \
    -e "s#{libPath}#$libpath_rendered#g" \
    -e "s/{dateFormat}/$dateFormat/g" \
    -e "s/{numberGroupSep}/$numberGroupSep/g" \
    -e "s/{numberDecimalSep}/$numberDecimalSep/g" \
    -e "s#{p2j_entry}#$p2j_entry#g" \
    -e "s/{pkgroot}/$pkgroot/g" \
    -e "s#{propath}#$propath#g" \
    -e "s#{search_path}#$searchpath#g" \
    -e "s/{path_separator}/$path_separator/g" \
    -e "s#{file_separator}#$sed_file_separator#g" \
    -e "s/{case_sensitive}/$case_sensitive/g" \
    -e "s/{os_user}/$user/g" \
    -e "s/{kbd_layout}/$keyboard/g" \
    -e "s/{dbname}/$defdatabase/g" \
    -e "s#{server_log}#$server_log#g" \
    -e "s#{client_log}#$client_log#g" \
    -e "s#{embedded_host}#$embedded_host#g" \
    -e "s#{admin_port}#$admin_port#g" \
    -e "s|{admin_console_pw}|$escaped_hash|g" \
    -e "s#{webclient_appcds_jvmargs}#$webclient_appcds_jvmargs#g" \
    -e "s/{webclient_memory}/$webclient_memory/g" \
    directory.xml.template > directory_tmp.xml
rc=$?
if [ $rc -ne 0 ]; then
   echo "ERROR: Could not create directory_tmp.xml rc=$rc"
   exit $rc
fi

# Handle Proxy portion as appropriate
if proxy=$(_getval "proxy" "$infile"); then
   forwarded_host=$(sub_getval "proxy" "forwarded_host" $embedded_host $infile)
   forwarded_proto=$(sub_getval "proxy" "forwarded_proto" "https" $infile)
   forwarded_prefix=$(sub_getval "proxy" "forwarded_prefix" "client" $infile)
   sed \
       -e "s/{forwarded_host}/$forwarded_host/g" \
       -e "s/{forwarded_proto}/$forwarded_proto/g" \
       -e "s/{forwarded_prefix}/$forwarded_prefix/g" \
       directory_proxy.xml.template > directory_proxy.xml
   rc=$?
   if [ $rc -ne 0 ]; then
      echo "ERROR: Could not create directory_proxy.xml rc=$rc"
      exit $rc
   fi
   directory_copy "directory_proxy.xml" "/server" "directory_tmp.xml" "/server"
   rm directory_proxy.xml
fi

# Handle DB portion as appropriate
dbdialect_h2="com.goldencode.p2j.persist.dialect.P2JH2Dialect"
dbdriver_h2="org.h2.Driver"
dbdialect_postgres="com.goldencode.p2j.persist.dialect.P2JPostgreSQLDialect"
dbdriver_postgres="org.postgresql.Driver"

# Loop through our list of DBs
for item in "${db_array[@]}"; do
   dbtype=$(sub_getval $item "dbtype" "h2" $infile)
   if [ "$dbtype" != "none" ]; then
      dbhost=$(sub_getval $item "dbhost" "localhost" $infile)
      if [ "$dbtype" == "postgres" ]; then
         dbport=$(sub_getval $item "dbport" "5432" $infile)
      elif [ "$dbtype" == "h2" ]; then
         dbpath=$(sub_getval $item "dbpath" "../db" $infile)
         pljava="TRUE"
      fi
      max_c3p0_pool=$(sub_getval $item "max_c3p0_pool" "20" $infile)
      collation=$(sub_getval $item "collation" "en_US@iso88591_fwd_basic" $infile)
      jdbc_url_h2="h2:${dbpath}/${item};DB_CLOSE_DELAY=-1;MV_STORE=FALSE;RTRIM=TRUE"
      jdbc_url_postgres="postgresql://${dbhost}:${dbport}/${item}"
      dbdialect=dbdialect_${dbtype}
      dbdialect=${!dbdialect}
      dbdriver=dbdriver_${dbtype}
      dbdriver=${!dbdriver}
      jdbc_url=jdbc_url_${dbtype}
      jdbc_url=${!jdbc_url}

      dbfile="directory_db.xml.${item}"

      sed \
          -e "s/{dbhost}/$dbhost/g" \
          -e "s/{dbport}/$dbport/g" \
          -e "s/{dbname}/$item/g" \
          -e "s/{dbuser}/$dbuser/g" \
          -e "s/{dbuserpass}/$dbuserpass/g" \
          -e "s/{dbadmin}/$dbadmin/g" \
          -e "s/{dbadminpass}/$dbadminpass/g" \
          -e "s/{dbdialect}/$dbdialect/g" \
          -e "s/{dbdriver}/$dbdriver/g" \
          -e "s/{max_c3p0_pool}/$max_c3p0_pool/g" \
          -e "s#{dbpath}#$dbdriver#g" \
          -e "s#{jdbc_url}#$jdbc_url#g" \
          -e "s/{pljava}/$pljava/g" \
          -e "s/{collation}/$collation/g" \
          directory_db.xml.template > $dbfile
      rc=$?
      if [ $rc -ne 0 ]; then
         echo "ERROR: Could not create ${dbfile} rc=$rc"
         exit $rc
      fi
   else
      dbfile="directory_nodb.xml"
      cp directory_nodb.xml.template $dbfile
   fi

   directory_copy $dbfile "/server" "directory_tmp.xml" "/server"
   rm $dbfile
done

# Loop through our list of brokers, if any
i=0
if load_array_from_json "brokers" "$infile" broker_array false; then
   for item in "${broker_array[@]}"; do
      ((i++))
      tname="broker${i}"
      client_xml_file=$(sub_getval $item "client_xml_file" "../etc/${tname}_client.xml" $infile)
      broker_process_name=$(sub_getval $item "broker_process_name" "${tname}_process" $infile)
      broker_process_description=$(sub_getval $item "broker_process_description" "${tname}_process" $infile)
      broker_process_name_alias=$(sub_getval $item "broker_process_name_alias" "${tname}" $infile)
      broker_name=$(sub_getval $item "broker_name" "${tname}" $infile)
      broker_os_user=$(sub_getval $item "broker_os_user" "${user}" $infile)
      broker_process_acl=$(sub_getval $item "broker_process_acl" "00000" $infile)
      spawner_path=$(sub_getval $item "spawner_path" "/opt/spawner/spawn" $infile)
      broker_client=$(sub_getval $item "broker_client" "localhost" $infile)
      broker_server=$(sub_getval $item "broker_server" $embedded_host $infile)
      storepath=$(sub_getval $item "storepath" "./deploy/security" $infile)
      logpath=$(sub_getval $item "logpath" "./deploy/logs" $infile)
      fwd_lib=$(sub_getval $item "fwd_lib" "/opt/fwd/build/lib" $infile)

      brokerfile="directory_broker${i}.xml"
      sed \
          -e "s/{broker_process_name}/${broker_process_name}/g" \
          -e "s/{broker_process_description}/${broker_process_description}/g" \
          -e "s/{broker_process_name_alias}/${broker_process_name_alias}/g" \
          -e "s/{broker_name}/${broker_name}/g" \
          -e "s/{broker_os_user}/${broker_os_user}/g" \
          -e "s/{broker_process_acl}/${broker_process_acl}/g" \
          directory_broker.xml.template > $brokerfile
      rc=$?
      if [ $rc -ne 0 ]; then
         echo "ERROR: Could not create ${brokerfile} rc=$rc"
         exit $rc
      fi

      directory_copy $brokerfile "/security" "directory_tmp.xml" "/security"
      directory_copy $brokerfile "/server" "directory_tmp.xml" "/server"
      rm $brokerfile

      cert_output="$(./gencert.sh "$item" -f directory_tmp.xml -s standard --emit-secrets --format=json --pkpw=${root_ca_pw})" \
         || { echo "ERROR: gencert.sh failed"; exit 1; }
      # Validate JSON structure
      if ! printf '%s' "$cert_output" | jq -e '.store_password and .keyentry_password' >/dev/null; then
         echo "ERROR: Invalid JSON from gencert.sh"
         printf '%s\n' "$cert_output"
         exit 1
      fi
      cp ${item}-private-key.store ${storepath}
      cp ${srvcerts_store} ${storepath}
      STORE_PASSWORD=$(printf '%s' "$cert_output" | jq -r '.store_password')
      KEYENTRY_PASSWORD=$(printf '%s' "$cert_output" | jq -r '.keyentry_password')
      store_pw_xml=$(xml_escape "$STORE_PASSWORD")
      store_pw_hash=$(escape_sed_replacement "$store_pw_xml")
      key_pw_xml=$(xml_escape "$KEYENTRY_PASSWORD")
      key_pw_hash=$(escape_sed_replacement "$key_pw_xml")
      srv_certs_pw_xml=$(xml_escape "$srv_certs_pw")
      srv_certs_hash=$(escape_sed_replacement "$srv_certs_pw_xml")

      # Setup the client.xml
      sed \
          -e "s#{logpath}#${logpath}#g" \
          -e "s/{broker_server}/${broker_server}/g" \
          -e "s#{storepath}#${storepath}#g" \
          -e "s/{broker_process_name_alias}/${broker_process_name_alias}/g" \
          -e "s#{spawner_path}#${spawner_path}#g" \
          -e "s/{broker_client}/${broker_client}/g" \
          -e "s/{broker_os_user}/${broker_os_user}/g" \
          -e "s#{fwd_lib}#${fwd_lib}#g" \
          -e "s/{srv_certs_pw}/${srv_certs_hash}/g" \
          -e "s/{pks_store_pw}/${store_pw_hash}/g" \
          -e "s/{pks_key_pw}/${key_pw_hash}/g" \
          -e "s/{log_rotation_limit}/${log_rotation_limit}/g" \
          -e "s/{log_rotation_count}/${log_rotation_count}/g" \
          broker_client.xml.template > $client_xml_file
      rc=$?
      if [ $rc -ne 0 ]; then
         echo "ERROR: Could not create $client_xml_file rc=$rc"
         exit $rc
      fi
   done
fi

$mysudo mv directory_tmp.xml $dirfile

exit 0
