#!/bin/bash

#set -x

# Default values
P2J_JAR="../lib/p2j.jar"
DIR_XML=""
APPCDS_DIR=""

show_usage()
{
   i=0;        usage[$i]="Usage: $(basename $0) [-f <directory.xml>] [-d <appcds_dir>] [path_to_p2j.jar]"
   i=$((i+1)); usage[$i]="Where:"
   i=$((i+1)); usage[$i]="path_to_p2j.jar \t= Path to p2j.jar (default=\"../lib/p2j.jar\")"
   i=$((i+1)); usage[$i]="-f | --file \t= Path to directory.xml (default=\"../server/directory.xml\")"
   i=$((i+1)); usage[$i]="-d | --dir \t= Path to output appcds folder (default=\"../appcds/client\")"
   i=$((i+1)); usage[$i]="-h | --help \t= Usage information"

   for i in "${usage[@]}"; do
      echo -e "$i"
   done
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        -h|--help|-\?)
            show_usage
            exit 1
            ;;
        -f|--file)
            DIR_XML="$2"
            shift 2
            ;;
        -d|--dir)
            APPCDS_DIR="$2"
            shift 2
            ;;
        *)
            if [[ "$1" == -* ]]; then
                echo "Unknown option: $1"
                show_usage
                exit 1
            fi
            # Positional argument
            P2J_JAR="$1"
            shift
            ;;
    esac
done

# Resolve DEPLOY_HOME relative to this script
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DEPLOY_HOME="$(cd "$SCRIPT_DIR/.." && pwd)"

# Ensure P2J_JAR is an absolute path if it exists
if [[ "$P2J_JAR" != /* ]]; then
    P2J_JAR="$PWD/$P2J_JAR"
fi

DIR_XML="${DIR_XML:-$DEPLOY_HOME/server/directory.xml}"
if [[ "$DIR_XML" != /* ]]; then
    DIR_XML="$PWD/$DIR_XML"
fi

APPCDS_DIR="${APPCDS_DIR:-$DEPLOY_HOME/appcds/client}"
if [[ "$APPCDS_DIR" != /* ]]; then
    APPCDS_DIR="$PWD/$APPCDS_DIR"
fi

if [ ! -f "$DIR_XML" ]; then
    echo "Error: $DIR_XML not found."
    exit 1
fi

TMP_PROPS=$(mktemp)
java -cp "$P2J_JAR" com.goldencode.util.JvmArgsExtractor -f "$DIR_XML" -o "$TMP_PROPS"

if [ $? -ne 0 ]; then
    echo "Error: Failed to extract JVM args."
    rm -f "$TMP_PROPS"
    exit 1
fi

# Read properties into dynamically named variables
while IFS='=' read -r key value; do
    if [[ $key == \#* ]] || [ -z "$key" ]; then
        continue
    fi
    key=$(echo "$key" | xargs)
    value="${value//\\:/:}"
    value="${value//\\=/=}"
    
    var_name="${key//./_}"
    var_name="${var_name//-/_}"
    declare "$var_name=$value"
done < "$TMP_PROPS"

rm -f "$TMP_PROPS"

# Remove existing appcds directory to prevent Java from reusing a stale .jsa archive.
# The JVM does not overwrite an existing SharedArchiveFile in-place; removing the
# directory guarantees a clean dump on every run.
if [ -d "$APPCDS_DIR" ]; then
    rm -rf "$APPCDS_DIR"
fi
mkdir -p "$APPCDS_DIR"

if [ -z "$appcds_clients" ]; then
    echo "No clients found for AppCDS."
    exit 0
fi

# Source the application name so getcp.sh can locate the application jar.
appname=""
[ -f "$DEPLOY_HOME/client/appname" ] && . "$DEPLOY_HOME/client/appname"

IFS=',' read -ra clients <<< "$appcds_clients"
for client_type in "${clients[@]}"; do
    client_type=$(echo "$client_type" | xargs)
    if [ -z "$client_type" ]; then
        continue
    fi
    
    echo "Processing client: $client_type"
    
    cp_var="appcds_classpath_$client_type"
    args_var="appcds_jvmargs_$client_type"
    
    client_args="${!args_var}"

    # JvmArgsExtractor only reports <libPath>/p2j.jar for the classpath. Build the
    # COMPLETE client runtime classpath the same way client.sh does -- via getcp.sh
    # run from the client dir -- and freeze it (below) to <type>.cpath. This makes
    # the classpath the archive is dumped against byte-for-byte identical to the one
    # the client replays (getcp.sh --appcds), so AppCDS's classpath check passes.
    # FWD_LIB points at the curated client deploy root (the parent of the lib dir
    # holding p2j.jar) so getcp.sh resolves the curated client library set.
    appcds_p2j="${!cp_var}"
    appcds_p2j="${appcds_p2j%%:*}"
    appcds_lib_dir="$(cd "$(dirname "$appcds_p2j")" 2>/dev/null && pwd)"
    appcds_fwd_root="$(dirname "$appcds_lib_dir")"
    client_cp="$(cd "$DEPLOY_HOME/client" && FWD_LIB="$appcds_fwd_root" "$DEPLOY_HOME/getcp.sh" "$appname" "$DEPLOY_HOME/client")"
    client_cp="${client_cp%:}"
    
    echo "JVM classpath for $client_type: $client_cp"
    echo "JVM args for $client_type: $client_args"
    
    base_lst=$(mktemp)
    runtime_lst=$(mktemp)
    
    # 1. LstExporter (run from the client dir so relative classpath entries resolve
    #    the same way they will at runtime)
    cd "$DEPLOY_HOME/client" || exit 1
    java -cp "$client_cp" com.goldencode.util.LstExporter \
        "com.goldencode.p2j.main.ClientDriver" \
        "com.goldencode.p2j.ui.client" \
        "-com.goldencode.p2j.persist" \
        "-com.goldencode.p2j.main.StandardServer" \
        "!com.goldencode.p2j.util" \
        "-o" "$base_lst"
        
    if [ $? -ne 0 ]; then
        echo "Error: LstExporter failed for $client_type"
        rm -f "$base_lst" "$runtime_lst"
        exit 1
    fi
    
    # 2. ClientDriver to dump runtime class list (also from the client dir)
    cd "$DEPLOY_HOME/client" || exit 1
    java -cp "$client_cp" \
        -Djava.library.path="$DEPLOY_HOME/lib" \
        -XX:DumpLoadedClassList="$runtime_lst" \
        com.goldencode.p2j.main.ClientDriver
        
    # 3. Concatenate. Add markers
    final_lst="$APPCDS_DIR/${client_type}.lst"
    sed -i '1i# This is base_lst' $base_lst
    sed -i '1i# This is runtime_lst' $runtime_lst
    cat "$base_lst" "$runtime_lst" > "$final_lst"

    # LstExporter copies SPI provider entries from META-INF/services/* verbatim, and
    # those files may carry inline comments that are legal per the ServiceLoader spec
    # (e.g. ecj's javax.tools.JavaCompiler lists
    #   org.eclipse.jdt...EclipseCompiler #Eclipse compiler).
    # The -Xshare:dump class-list parser rejects a class name followed by such a
    # trailing comment, so strip any inline "#..." while leaving full-line comments
    # (lines that begin with #) intact.
    sed -i 's/\([^[:space:]]\)[[:space:]]*#.*$/\1/' "$final_lst"
    
    # 4. Build JSA archive
    cd "$DEPLOY_HOME/client" || exit 1
    
    # We must split client_args on spaces properly without quotes
    # so that -Xmx512m -Dfoo=bar are treated as separate args
    java -cp "$client_cp" \
        -Djava.library.path="$DEPLOY_HOME/lib" \
        -Xshare:dump \
        -XX:SharedClassListFile="$APPCDS_DIR/${client_type}.lst" \
        -XX:SharedArchiveFile="$APPCDS_DIR/${client_type}.jsa" \
        $client_args \
        com.goldencode.p2j.main.ClientDriver
        
    if [ $? -ne 0 ]; then
        echo "Error: JSA archive generation failed for $client_type"
        rm -f "$base_lst" "$runtime_lst"
        exit 1
    fi

    # Record the exact classpath the archive was dumped against, alongside the
    # .jsa/.lst. The client runtime (getcp.sh --appcds) reads this file so its
    # classpath matches the archive. AppCDS requires the dumped classpath to be
    # a prefix of the runtime classpath, so these must stay in lock-step. The
    # client never has access to directory.xml, which is why this is published
    # here at prepare time instead.
    echo "$client_cp" > "$APPCDS_DIR/${client_type}.cpath"

    #rm -f "$base_lst" "$runtime_lst"
done

echo "AppCDS deployment completed successfully."
