#!/bin/bash
# Info: Script to install Cosmian KMS
# Author: Provisioning System
# Release: 1.0
# Date: 2025-07-24

USAGE="install-kms.sh"
[ "$1" == "-h" ] && echo "$USAGE" && exit 1

[ -r "env-kms" ] && . ./env-kms

KMS_VERSION=${KMS_VERSION:-4.17.0}

# Determine architecture
ARCH="$(uname -m)"
case $ARCH in
    x86_64) ARCH="x86_64" ;;
    aarch64) ARCH="aarch64" ;;
    *) echo "Unsupported architecture: $ARCH" && exit 1 ;;
esac

KMS_URL=https://github.com/Cosmian/kms/releases/download
KMS_BINARY=v${KMS_VERSION}/cosmian_kms_server-${KMS_VERSION}-${ARCH}-unknown-linux-gnu
KMS_CLI_BINARY=v${KMS_VERSION}/ckms-${KMS_VERSION}-${ARCH}-unknown-linux-gnu

KMS_RUN_PATH=${KMS_RUN_PATH:-/usr/local/bin/cosmian_kms}
KMS_CLI_PATH=${KMS_CLI_PATH:-/usr/local/bin/ckms}
KMS_SYSTEMCTL_MODE=${KMS_SYSTEMCTL_MODE:-enabled}

KMS_CONFIG_PATH=${KMS_CONFIG_PATH:-/etc/cosmian}
KMS_WORK_PATH=${KMS_WORK_PATH:-/var/lib/kms}
KMS_CONFIG_FILE=${KMS_CONFIG_FILE:-kms.toml}

KMS_RUN_USER=${KMS_RUN_USER:-kms}
KMS_RUN_GROUP=${KMS_RUN_GROUP:-kms}
KMS_RUN_USER_HOME=${KMS_RUN_USER_HOME:-/home/kms}

KMS_PORT=${KMS_PORT:-9998}
KMS_LOG_LEVEL=${KMS_LOG_LEVEL:-info}
KMS_DATABASE_TYPE=${KMS_DATABASE_TYPE:-sqlite}
KMS_DATABASE_PATH=${KMS_DATABASE_PATH:-/var/lib/kms/kms.db}

echo "Installing Cosmian KMS ${KMS_VERSION}..."

# Install dependencies
echo "Installing dependencies..."
if command -v apt-get >/dev/null 2>&1; then
    apt-get update
    apt-get install -y curl ca-certificates openssl libssl3
elif command -v yum >/dev/null 2>&1; then
    yum update -y
    yum install -y curl ca-certificates openssl openssl-libs
elif command -v dnf >/dev/null 2>&1; then
    dnf update -y
    dnf install -y curl ca-certificates openssl openssl-libs
else
    echo "Package manager not found. Please install curl, ca-certificates, and openssl manually."
    exit 1
fi

# Create user and group
if ! id "$KMS_RUN_USER" &>/dev/null; then
    groupadd -r "$KMS_RUN_GROUP"
    useradd -r -g "$KMS_RUN_GROUP" -d "$KMS_RUN_USER_HOME" -s /bin/bash -c "Cosmian KMS service user" "$KMS_RUN_USER"
fi

# Create directories
mkdir -p "$KMS_CONFIG_PATH"
mkdir -p "$KMS_WORK_PATH"
mkdir -p "$KMS_RUN_USER_HOME"
mkdir -p "$(dirname "$KMS_DATABASE_PATH")"

# Download and install KMS server
cd /tmp
echo "Downloading KMS server from ${KMS_URL}/${KMS_BINARY}..."
curl -L -o cosmian_kms_server "${KMS_URL}/${KMS_BINARY}"

if [ ! -f "cosmian_kms_server" ]; then
    echo "Failed to download KMS server binary"
    exit 1
fi

# Download and install KMS CLI
echo "Downloading KMS CLI from ${KMS_URL}/${KMS_CLI_BINARY}..."
curl -L -o ckms "${KMS_URL}/${KMS_CLI_BINARY}"

if [ ! -f "ckms" ]; then
    echo "Failed to download KMS CLI binary"
    exit 1
fi

# Install binaries
chmod +x cosmian_kms_server ckms
mv cosmian_kms_server "$(dirname "$KMS_RUN_PATH")/"
mv ckms "$(dirname "$KMS_CLI_PATH")/"

# Create configuration file from template if it exists
if [ -f "kms.toml.j2" ] && command -v jinja2 >/dev/null 2>&1; then
    echo "Generating configuration file..."
    # This would typically be handled by the provisioning system's template engine
    cp kms.toml.j2 "$KMS_CONFIG_PATH/$KMS_CONFIG_FILE.template"
else
    # Create basic configuration file
    cat > "$KMS_CONFIG_PATH/$KMS_CONFIG_FILE" << EOF
[server]
port = $KMS_PORT
bind_addr = "0.0.0.0"

[database]
database_type = "$KMS_DATABASE_TYPE"
$(if [ "$KMS_DATABASE_TYPE" = "sqlite" ]; then echo "database_path = \"$KMS_DATABASE_PATH\""; fi)

[logging]
level = "$KMS_LOG_LEVEL"
EOF
fi

# Set ownership
chown -R "$KMS_RUN_USER:$KMS_RUN_GROUP" "$KMS_WORK_PATH"
chown -R "$KMS_RUN_USER:$KMS_RUN_GROUP" "$KMS_RUN_USER_HOME"
chown -R "$KMS_RUN_USER:$KMS_RUN_GROUP" "$KMS_CONFIG_PATH"

# Initialize database if using SQLite
if [ "$KMS_DATABASE_TYPE" = "sqlite" ]; then
    # Ensure database directory exists and has proper permissions
    mkdir -p "$(dirname "$KMS_DATABASE_PATH")"
    chown -R "$KMS_RUN_USER:$KMS_RUN_GROUP" "$(dirname "$KMS_DATABASE_PATH")"
fi

# Create systemd service file
cat > /etc/systemd/system/cosmian-kms.service << EOF
[Unit]
Description=Cosmian KMS Server
Documentation=https://github.com/Cosmian/kms
After=network.target

[Service]
Type=simple
User=$KMS_RUN_USER
Group=$KMS_RUN_GROUP
Environment=COSMIAN_KMS_CONF=$KMS_CONFIG_PATH/$KMS_CONFIG_FILE
Environment=RUST_LOG=$KMS_LOG_LEVEL
WorkingDirectory=$KMS_WORK_PATH
ExecStart=$KMS_RUN_PATH --config-file $KMS_CONFIG_PATH/$KMS_CONFIG_FILE
Restart=always
RestartSec=10

# Security settings  
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=$KMS_WORK_PATH $KMS_CONFIG_PATH
CapabilityBoundingSet=CAP_NET_BIND_SERVICE

[Install]
WantedBy=multi-user.target
EOF

# Enable and start service
systemctl daemon-reload
systemctl "$KMS_SYSTEMCTL_MODE" cosmian-kms.service

if [ "$KMS_SYSTEMCTL_MODE" = "enabled" ]; then
    systemctl start cosmian-kms.service
fi

# Cleanup
cd /
rm -rf /tmp/cosmian_kms_server /tmp/ckms

echo "Cosmian KMS installation completed!"
echo "Service: cosmian-kms.service"
echo "KMS Server available at: http://$(hostname):$KMS_PORT"
echo "CLI tool: $KMS_CLI_PATH"
echo "Configuration: $KMS_CONFIG_PATH/$KMS_CONFIG_FILE"
echo "Data directory: $KMS_WORK_PATH"

# Display service status
if systemctl is-active --quiet cosmian-kms.service; then
    echo "✅ KMS service is running"
else
    echo "⚠️  KMS service status:"
    systemctl status cosmian-kms.service --no-pager -l
fi