#!/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
rm -fr /tmp/vault-test/data /tmp/vault-test/config
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 = false
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 wget -q -O- --no-check-certificate 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 with the server command
echo "Building and running the vault-hier server..."
cargo build && cargo run server --vault-addr "$VAULT_ADDR" &
SERVER_PID=$!

# Wait for the server to start
echo "Waiting for the server to start..."
sleep 5

# Test the server with some client operations
echo "Testing the client operations..."

# Create a sample file for testing
echo "Creating a sample file for testing..."
echo "This is a test document" > test_document.txt

# Test login
echo "Testing login with legal1 user..."
LOGIN_OUTPUT=$(cargo run login --username legal1 --password legal1pass)
TOKEN=$(echo "$LOGIN_OUTPUT" | grep "Token:" | awk '{print $2}')

if [ -z "$TOKEN" ]; then
    echo "Login failed. Could not get token."
    cat test_document.txt
    kill -9 $SERVER_PID
    kill -9 $VAULT_PID
    rm "$VAULT_PID_FILE"
    exit 1
fi

echo "Login successful, got token: ${TOKEN:0:8}..."

# Test upload
echo "Testing document upload..."
UPLOAD_OUTPUT=$(cargo run upload --name "Test Document" --file test_document.txt)
DOC_ID=$(echo "$UPLOAD_OUTPUT" | grep "Document ID:" | awk '{print $3}')

if [ -z "$DOC_ID" ]; then
    echo "Upload failed. Could not get document ID."
    kill -9 $SERVER_PID
    kill -9 $VAULT_PID
    rm "$VAULT_PID_FILE"
    exit 1
fi

echo "Upload successful, got document ID: $DOC_ID"

# Test signing
echo "Testing document signing..."
SIGN_OUTPUT=$(cargo run sign --document-id "$DOC_ID" --username legal1 --token "$TOKEN")

if echo "$SIGN_OUTPUT" | grep -q "Document signed successfully"; then
    echo "Document signed successfully"
else
    echo "Signing failed"
    kill -9 $SERVER_PID
    kill -9 $VAULT_PID
    rm "$VAULT_PID_FILE"
    exit 1
fi

# Test verification
echo "Testing document verification..."
VERIFY_OUTPUT=$(cargo run verify --document-id "$DOC_ID")

if echo "$VERIFY_OUTPUT" | grep -q "Verification result"; then
    echo "Verification successful"
else
    echo "Verification failed"
    kill -9 $SERVER_PID
    kill -9 $VAULT_PID
    rm "$VAULT_PID_FILE"
    exit 1
fi

# Check if the credentials file was created
if [ -f "vault-credentials.txt" ] || [ -f "vault-credentials.json" ]; then
    echo "Test successful! Credentials were saved"

    if [ -f "vault-credentials.txt" ]; then
        # 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"
    fi
else
    echo "Warning: Credentials file was not created."
fi

echo -e "\nTest complete! Cleaning up..."
# Stop vault-hier server
kill -9 $SERVER_PID

# 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
rm -f test_document.txt

echo "All cleaned up. Test successful!"