#!/usr/bin/bash

parse_json() {
    local json="$1"
    local query="$2"
    echo "$json" | jq -r "$query"
}

generate_unique_id() {
    echo $((RANDOM + 10000))
}

remove_license_markers() {
    local license_content="$1"
    # Remove license markers and clean the content
    echo "$license_content" | awk '
    BEGIN { 
        RS="-----END LICENSE FILE-----";
        FS="-----BEGIN LICENSE FILE-----";
    }
    {
        gsub(/^[[:space:]]+|[[:space:]]+$/, "", $2);
        gsub(/\n/, "", $2);
        print $2;
    }'
}

# Find the first .out file in the current directory
LICENSE_FILE=$(ls *.out 2>/dev/null | head -n 1)

if [ -z "$LICENSE_FILE" ]; then
    echo "Error: No .out file found in the current directory."
    exit 1
fi

echo "Using license file: $LICENSE_FILE"

# Read the license string from the .out file
LICENSE_STRING=$(cat "$LICENSE_FILE")

# Compile and run LicenseParser
mkdir -p com/authentrend/licenseparser
cp LicenseParser.java com/authentrend/licenseparser/
javac -cp "./libs/*" com/authentrend/licenseparser/LicenseParser.java

# Create a temporary file for the license string
TEMP_LICENSE_FILE=$(mktemp)
echo "$LICENSE_STRING" > "$TEMP_LICENSE_FILE"


parse_result=$(java -cp .:./libs/* com.authentrend.licenseparser.LicenseParser "$TEMP_LICENSE_FILE")

# Remove the temporary file
rm "$TEMP_LICENSE_FILE"

# Clean up compiled files
rm -rf com

# Extract AUTHFI_APIPATH and AUTHFI_ACCESSPOINT
AUTHFI_APIPATH=$(parse_json "$parse_result" '.rpData[0].authFiApiKey')
AUTHFI_URL=$(parse_json "$parse_result" '.data.authFiUrl')
AUTHFI_ACCESSPOINT=$(parse_json "$parse_result" '.rpData[0].authFiApiAccessPoint')
ATKEY_URL=$(parse_json "$parse_result" '.data.state.productState.url')
MAX_USERS=$(parse_json "$parse_result" '.data.state.productState.maxUsers')
AUTHENTICATION_LIMIT=$(parse_json "$parse_result" '.data.state.productState.authenticationLimit')
ADMIN_EMAILS=$(parse_json "$parse_result" '.data.state.productState.productAdmins')
EXPIRE_DATE=$(parse_json "$parse_result" '.data.state.productState.expireDate')
CURRENT_EPOCH=$(date +%s)

CLEAN_LICENSE_STRING=$(remove_license_markers "$LICENSE_STRING")


[ -z "$AUTHFI_APIPATH" ] || [ -z "$AUTHFI_ACCESSPOINT" ] && { echo "Failed to parse required values from the license."; exit 1; }

if [ -f docker-compose.yml ]; then
    awk -v apipath="$AUTHFI_APIPATH" -v accesspoint="$AUTHFI_URL"/"$AUTHFI_ACCESSPOINT" -v server_url="$ATKEY_URL" '
    /SERVER_URL=/ {$0 = "      - SERVER_URL=" server_url}
    /AUTHFI_APIPATH=/ {$0 = "      - AUTHFI_APIPATH=" apipath}
    /AUTHFI_ACCESSPOINT=/ {$0 = "      - AUTHFI_ACCESSPOINT=" accesspoint}
    {print}
    ' docker-compose.yml > docker-compose.yml.tmp && mv docker-compose.yml.tmp docker-compose.yml
fi

systemctl restart atkeylogin

exit 0