#!/bin/sh
set -e

# Source Vault-rendered environment if available
if [ -f /vault/secrets/.env ]; then
    echo "Loading environment from Vault..."
    set -a
    . /vault/secrets/.env
    set +a
fi

# Start the application in background
/app/nexus &
APP_PID=$!

# Write PID for Vault Agent to signal on credential rotation
# Use shared volume so vault-agent can read it
echo $APP_PID > /vault/secrets/nexus.pid
echo "Nexus started with PID $APP_PID"

# Forward signals to the app
trap "kill -TERM $APP_PID" TERM INT
trap "kill -HUP $APP_PID" HUP

# Wait for app to exit
wait $APP_PID
EXIT_CODE=$?

# Clean up
rm -f /vault/secrets/nexus.pid

exit $EXIT_CODE
