#!/bin/bash

# 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

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_cp="${!cp_var}"
    client_args="${!args_var}"

    # Directory holding p2j.jar (and its manifest-referenced jars). Used only when
    # INCLUDE_STATIC=true, to give LstExporter an explicit classpath to analyze --
    # the manifest expansion is not visible via java.class.path.
    appcds_lib_dir="$(cd "$(dirname "${client_cp%%:*}")" 2>/dev/null && pwd)"

    echo "JVM classpath for $client_type: $client_cp"
    echo "JVM args for $client_type: $client_args"
    
    base_lst=$(mktemp)
    runtime_lst=$(mktemp)

    # 1. (Optional) LstExporter static reachability. OFF by default: walking the whole
    #    classpath yields ~18k classes / ~140MB .jsa, while a real client loads ~2k --
    #    the bloat balloons per-client memory with no benefit. Enable INCLUDE_STATIC=true
    #    for broader coverage. It needs an EXPLICIT classpath (the lib dir's jars),
    #    because under -cp p2j.jar the manifest-referenced jars are invisible to it.
    if [ "${INCLUDE_STATIC:-false}" = "true" ]; then
        static_cp="$client_cp"
        for j in "$appcds_lib_dir"/*.jar; do
            [ "$j" = "${client_cp%%:*}" ] || static_cp="$static_cp:$j"
        done
        cd "$DEPLOY_HOME/client" || exit 1
        java -cp "$static_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
    fi

    # 2. ClientDriver to dump the runtime (actually-loaded) class list.
    cd /tmp || exit 1
    java -cp "$client_cp" \
        -Djava.library.path="$DEPLOY_HOME/lib" \
        -XX:DumpLoadedClassList="$runtime_lst" \
        com.goldencode.p2j.main.ClientDriver
        
    # 3. Assemble the class list. Default = runtime-loaded set only (lean archive that
    #    matches what the client actually uses). Prepend the static set only when
    #    INCLUDE_STATIC produced one.
    final_lst="$APPCDS_DIR/${client_type}.lst"
    if [ -s "$base_lst" ]; then
        sed -i '1i# base_lst (static)' "$base_lst"
        sed -i '1i# runtime_lst' "$runtime_lst"
        cat "$base_lst" "$runtime_lst" > "$final_lst"
    else
        cp "$runtime_lst" "$final_lst"
    fi

    # 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."
