#!/bin/bash
set -e

AGENT_HOME="/home/apminsight/dotnet"
AGENT_DIR="$AGENT_HOME/ApmInsightDotNetCoreAgent"

echo "Step 1: Setting environment variables."

export CORECLR_ENABLE_PROFILING=1
export CORECLR_PROFILER="{9D363A5F-ED5F-4AAC-B456-75AFFA6AA0C8}"
export CORECLR_SITE24X7_HOME="$AGENT_DIR"
export CORECLR_PROFILER_PATH_64="$AGENT_DIR/x64/libClrProfilerAgent.so"
export CORECLR_PROFILER_PATH_32="$AGENT_DIR/x86/libClrProfilerAgent.so"
export DOTNET_STARTUP_HOOKS="$AGENT_DIR/netstandard2.0/DotNetAgent.Loader.dll"
export MANAGEENGINE_COMMUNICATION_MODE="ExporterService"

if [ -d "$AGENT_DIR" ]; then
	echo "APM Insight agent directory already exists. Skipping installation..."
else
	echo "Agent directory not found. Proceeding with installation..."

	echo "Step 2: Updating packages."
	apt-get update

	echo "Step 3: Installing packages."
	apt-get install -y wget unzip procps vim-common

	echo "Step 3: Downloading APM agent."
	wget --no-hsts https://staticdownloads.site24x7.com/apminsight/agents/dotnet/apminsight-dotnetcoreagent-linux.sh
	chmod +x apminsight-dotnetcoreagent-linux.sh

	echo "Step 4: Installing APM agent."
	printf "A\n" | ./apminsight-dotnetcoreagent-linux.sh -Destination "$AGENT_HOME"
	
	rm -f apminsight-dotnetcoreagent-linux.sh

	echo "Step 5: Installing Data Exporter."
	wget --no-hsts -O InstallDataExporter.sh https://staticdownloads.site24x7.com/apminsight/S247DataExporter/linux/InstallDataExporter.sh
	chmod +x InstallDataExporter.sh
	sh InstallDataExporter.sh
	rm -f InstallDataExporter.sh
fi

# YOUR APPLICATION STARTUP COMMAND GOES HERE