#!/bin/bash
# Info: Cosmian KMS preparation script
# Author: Provisioning System
# Release: 1.0

echo "Preparing Cosmian KMS installation..."

# Load environment variables
[ -r "env-kms" ] && . ./env-kms

# Check if required tools are available
command -v curl >/dev/null 2>&1 || { echo "curl is required but not installed." >&2; exit 1; }
command -v systemctl >/dev/null 2>&1 || { echo "systemctl is required but not installed." >&2; exit 1; }

# Check OpenSSL version (KMS requires OpenSSL v3.2.0+)
if command -v openssl >/dev/null 2>&1; then
    OPENSSL_VERSION=$(openssl version | awk '{print $2}')
    echo "Found OpenSSL version: $OPENSSL_VERSION"
    
    # Basic version check (simplified)
    MAJOR_VERSION=$(echo "$OPENSSL_VERSION" | cut -d. -f1)
    if [ "$MAJOR_VERSION" -lt "3" ]; then
        echo "Warning: OpenSSL version 3.2.0+ is recommended for KMS"
    fi
else
    echo "Warning: OpenSSL not found. KMS requires OpenSSL v3.2.0+"
fi

# Validate configuration
if [ -z "$KMS_VERSION" ]; then
    echo "KMS_VERSION must be set" >&2
    exit 1
fi

if [ -z "$KMS_PORT" ]; then
    echo "KMS_PORT must be set" >&2
    exit 1
fi

# Check port availability
if command -v netstat >/dev/null 2>&1; then
    if netstat -tuln | grep -q ":${KMS_PORT:-9998} "; then
        echo "Warning: Port ${KMS_PORT:-9998} appears to be in use"
    fi
elif command -v ss >/dev/null 2>&1; then
    if ss -tuln | grep -q ":${KMS_PORT:-9998} "; then
        echo "Warning: Port ${KMS_PORT:-9998} appears to be in use"
    fi
fi

# Validate database configuration
case "${KMS_DATABASE_TYPE:-sqlite}" in
    sqlite)
        echo "Using SQLite database"
        ;;
    mysql)
        if [ -z "$KMS_DATABASE_HOST" ] || [ -z "$KMS_DATABASE_USERNAME" ] || [ -z "$KMS_DATABASE_PASSWORD" ]; then
            echo "MySQL requires host, username, and password configuration" >&2
            exit 1
        fi
        ;;
    postgresql)
        if [ -z "$KMS_DATABASE_HOST" ] || [ -z "$KMS_DATABASE_USERNAME" ] || [ -z "$KMS_DATABASE_PASSWORD" ]; then
            echo "PostgreSQL requires host, username, and password configuration" >&2
            exit 1
        fi
        ;;
    redis)
        if [ -z "$KMS_DATABASE_HOST" ]; then
            echo "Redis requires host configuration" >&2
            exit 1
        fi
        ;;
    *)
        echo "Unsupported database type: ${KMS_DATABASE_TYPE}" >&2
        exit 1
        ;;
esac

echo "Preparation completed successfully."