#!/usr/bin/env bash
set -e

# Detect OS and handle accordingly
if [[ "$OSTYPE" == "darwin"* ]]; then
    # macOS
    export VAULT_ADDR="http://127.0.0.1:8200"
    VAULT_PID_FILE="/tmp/vault.pid"
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
    # Linux
    export VAULT_ADDR="http://127.0.0.1:8200"
    VAULT_PID_FILE="/tmp/vault.pid"
else
    # Windows or other
    export VAULT_ADDR="http://127.0.0.1:8200"
    VAULT_PID_FILE="./vault.pid"
fi

# Check if Vault is installed
if ! command -v vault &> /dev/null; then
    echo "Vault is not installed. Please install it first."
    exit 1
fi

# Check if there's already a Vault process running
if [ -f "$VAULT_PID_FILE" ]; then
    VAULT_PID=$(cat "$VAULT_PID_FILE")
    if ps -p $VAULT_PID > /dev/null; then
        echo "Vault is already running with PID $VAULT_PID"
        echo "Stopping the existing Vault server..."
        kill -9 $VAULT_PID
        rm "$VAULT_PID_FILE"
        # Wait for the port to be released
        sleep 2
    else
        echo "Vault PID file exists but the process is not running. Removing stale PID file."
        rm "$VAULT_PID_FILE"
    fi
fi

echo "Starting Vault server in non-dev mode..."

# Create temporary config file
mkdir -p /tmp/vault-test/data /tmp/vault-test/config

cat > /tmp/vault-test/config/vault.hcl << EOF
storage "file" {
  path = "/tmp/vault-test/data"
}

listener "tcp" {
  address     = "127.0.0.1:8200"
  tls_disable = "true"
}

disable_mlock = true
ui = true
EOF

vault server -config=/tmp/vault-test/config/vault.hcl > ./vault_server.log 2>&1 &
VAULT_PID=$!
echo $VAULT_PID > "$VAULT_PID_FILE"

echo "Vault server started with PID $VAULT_PID"
echo "Vault server is running at $VAULT_ADDR"

# Wait for Vault to start
echo "Waiting for Vault to start..."
sleep 5

# Check if Vault is up and running
for i in {1..10}; do
  if curl -fs -m 1 http://127.0.0.1:8200/v1/sys/health?standbyok=true\&sealedok=true\&uninitok=true > /dev/null 2>&1; then
    echo "Vault is up and running!"
    break
  fi
  
  if [ $i -eq 10 ]; then
    echo "Timed out waiting for Vault to become available"
    exit 1
  fi
  
  echo "Vault is unavailable - sleeping (attempt $i/10)"
  sleep 2
done

# Build and run the Rust application
echo "Building and running the Rust application..."
cargo build && cargo run

# Check if the credentials file was created
if [ -f "vault-credentials.txt" ]; then
    echo "Test successful! Credentials were saved to vault-credentials.txt"
    # Extract the unseal keys for demonstration
    UNSEAL_KEYS=$(grep "Key" vault-credentials.txt | head -n 3 | awk '{print $3}')
    ROOT_TOKEN=$(grep "Root Token" vault-credentials.txt | awk '{print $3}')
    
    echo "Root Token: $ROOT_TOKEN"
    echo "First 3 Unseal Keys (needed for threshold):"
    echo "$UNSEAL_KEYS"
    
    # Clean up temporary files
    rm -f vault-credentials.txt
else
    echo "Test failed! Credentials file was not created."
    exit 1
fi

echo -e "\nTest complete! Cleaning up..."
# Stop Vault server
kill -9 $VAULT_PID
rm "$VAULT_PID_FILE"

# Clean up test environment
rm -rf /tmp/vault-test
rm -f ./vault_server.log

echo "All cleaned up. Test successful!"