#!/usr/bin/env bash
set -eo pipefail

function usage()
{
   cat <<EOF
Usage: $0 [-d] [-x <bootstrap xml>] [-p<path to FWD libraries>] [-f<slf4j-impl.jar file>] [-n<path to native spawner>] [-c<srv-certs.store file>] [-t<postbuild.sh tool>]

Position spawner as needed by current configuration

Where:
       -d = dryrun (just display commands)
       -x <bootstrap xml> = use <bootstrap xml> as the bootstrap file (def=server.xml)
       -p = Location of FWD libraries p2j.jar and fwd-slf4j.jar (if no -f specified). \"FWD_LIB\" will be used as a fallback if default is not valid. (def=${p2j_lib})
       -f = Location of file to be placed in slf4j-impl.jar destination (def=fwd-slf4j.jar in -p location or FWD_LIB)
       -n = Location of built native spawner (def=${spawn_prog}, unless -p specified, which will change the default location)
       -c = Location of srv-certs.store file (def=${srv_certs})
       -t = Location of postbuild.sh tool (def=${postbuild}, unless -p specified, which will change the default location)

 -? or -h or --help = show usage.
EOF
}

# defaults
BOOTSTRAP="server.xml"
pwd=$PWD
p2j_lib=${pwd}/p2j/build/lib
deploy_home=${pwd}/deploy
srv_certs=${deploy_home}/server/srv-certs.store
build_home=${pwd}/build
p2j_root=${pwd}/p2j
postbuild=${p2j_root}/src/native/postbuild.sh
spawn_prog=${p2j_root}/build/native/spawn

while getopts ":h?d-x:p:f:n:c:t:" opt; do
   case "$opt" in
      d  ) mycmd="echo" ;;
      x  ) BOOTSTRAP=$OPTARG ;;
      p  ) p2j_passed=true
           p2j_lib=$OPTARG ;;
      f  ) slf4j_impl=$OPTARG ;;
      n  ) spawn_passed=true
           spawn_prog=$OPTARG ;;
      c  ) srv_certs=$OPTARG ;;
      t  ) postbuild_passed=true
           postbuild=$OPTARG ;;
      -  ) case ${OPTARG} in
             "help" ) usage
                      exit 1 ;;
              * ) echo "Unknown option: --${OPTARG}"
                  usage
                  exit 1 ;;
           esac
           ;;
      h | \? ) if [[ "$OPTARG" == "?" || "$opt" == "h" ]]; then
                  usage
                  exit 1
               else
                  echo "Unknown option: -${OPTARG}"
                  usage
                  exit 1
               fi
               ;;
   esac
done
shift $(($OPTIND - 1))

# --- Step 1: Extract directory filename from bootstrap ---
if [[ ! -f "$BOOTSTRAP" ]]; then
   echo "ERROR: Bootstrap XML '$BOOTSTRAP' not found"
   exit 1
fi

DIR_XML=$(xmlstarlet sel -t -v '/node/directory/xml/@filename' -n "$BOOTSTRAP")
if [[ -z "$DIR_XML" ]]; then
    echo "ERROR: Could not find <directory><xml filename=\"...\"/> in $BOOTSTRAP"
    exit 1
elif [[ ! -f "$DIR_XML" ]]; then
    echo "ERROR: Directory XML '$DIR_XML' does not exist"
    exit 1
fi

# --- Step 2: Extract all configured spawners ---
# These are values like /opt/spawner/spawn
readarray -t SPAWNERS < <(
   xmlstarlet sel -t \
       -m '//node[@name="clientConfig"]/node[@name="spawner"]/node-attribute[@name="value"]' \
       -v '@value' -n \
       "$DIR_XML"
)

if [[ ${#SPAWNERS[@]} -eq 0 ]]; then
   echo "No spawners found in directory XML."
   exit 0
fi

# --- Step 3: Extract unique parent directories ---
# example: /opt/spawner/spawn -> /opt/spawner
declare -A UNIQUE_DIRS=()
for sp in "${SPAWNERS[@]}"; do
   parent=$(dirname "$sp")
   UNIQUE_DIRS["$parent"]=1
done

# Set new p2j root, if path to lib is passed
[ -n "$p2j_passed" ] && p2j_root=$(dirname "$p2j_lib")

# Set defaults when no options passed and spawn/postbuild.sh are not found (or bail)
if [ -f "/opt/fwd-deploy/spawner/spawn" ] && [ -z "$p2j_passed" ] && [ -z "$spawn_passed" ] && [ ! -f "$spawn_prog" ]; then
   spawn_prog=/opt/fwd-deploy/spawner/spawn
fi
if [ ! -f "$spawn_prog" ]; then
   echo "Error: $spawn_prog not found. Exiting."
   exit 1
fi
if [ -f "/opt/fwd-deploy/spawner/postbuild.sh" ] && [ -z "$p2j_passed" ] && [ -z "$postbuild_passed" ] && [ ! -f "$postbuild" ]; then
   postbuild=/opt/fwd-deploy/spawner/postbuild.sh
fi
if [ ! -f "$postbuild" ]; then
   echo "Error: $postbuild not found. Exiting."
   exit 1
fi

# Find default locations when using FWD_LIB and not overridden by -p
if [ -n "$FWD_LIB" ] && [ -z "$p2j_passed" ]; then
   if [ ! -d "${p2j_root}/build/lib" ]; then
      p2j_lib=$FWD_LIB/build/lib
      if [ -f "$FWD_LIB/lib/p2j.jar" ]; then
         p2j_lib=$FWD_LIB/lib
      fi
      [ -z "$spawn_passed" ] && spawn_prog=${p2j_root}/build/native/spawn
      [ -z "$postbuild_passed" ] && postbuild=${p2j_root}/src/native/postbuild.sh
   fi
fi
# Set the additional parameters to postbuild for p2j and fwd-slf4j
p2j_jar=${p2j_lib}/p2j.jar
[ -z "$slf4j_impl" ] && slf4j_impl=${p2j_lib}/fwd-slf4j.jar

# --- This is where we would copy the spawn to each of the unique directories found ---
for fspawn in "${!UNIQUE_DIRS[@]}"; do
   echo "Processing $fspawn ..."
   # Use sudo if elevation is required (destination for spawn is outside $HOME and we are *not* root)
   [[ "$fspawn"* != "$HOME"* ]] && [[ $(whoami) != "root" ]] && mysudo="sudo"

   # Position the spawner files
   $mycmd $mysudo $postbuild $fspawn $spawn_prog $srv_certs $p2j_jar $slf4j_impl
   $mycmd $mysudo chmod gou+rx $fspawn
done
