#!/bin/bash
# SeekDB start script
# This script reads configuration from /etc/oceanbase/seekdb.cnf and starts observer

CONFIG_FILE="/etc/oceanbase/seekdb.cnf"
BASE_DIR="/var/lib/oceanbase"
SYSTEMD_PID_FILE="$BASE_DIR/run/observer.pid"

# Check if config file exists
if [ ! -f "$CONFIG_FILE" ]; then
    echo "Error: Configuration file $CONFIG_FILE not found"
    exit 1
fi

# Initialize additional parameters
ADDITIONAL_PARAMS=""

# Function to read configuration file and build command line arguments
read_config() {
    while IFS= read -r line; do
        # Skip empty lines and comments
        [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue

        key="${line%%=*}"
        value="${line#*=}"

        # Trim whitespace
        key="$(echo "$key" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"
        value="$(echo "$value" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"

        case "$key" in
            "port")
                ADDITIONAL_PARAMS="$ADDITIONAL_PARAMS --port=$value"
                ;;
            "base-dir")
                BASE_DIR="$value"
                ;;
            "data-dir")
                ADDITIONAL_PARAMS="$ADDITIONAL_PARAMS --data-dir=$value"
                ;;
            "redo-dir")
                ADDITIONAL_PARAMS="$ADDITIONAL_PARAMS --redo-dir=$value"
                ;;
            *)
                ADDITIONAL_PARAMS="$ADDITIONAL_PARAMS --parameter $key=$value"
                ;;
        esac
    done < "$CONFIG_FILE"
}

# Check if data-dir is specified and not empty
read_config

# Build final command
CMD="/usr/bin/observer --base-dir=$BASE_DIR $ADDITIONAL_PARAMS"

echo "Starting seekdb with command: $CMD"
echo "Configuration loaded from: $CONFIG_FILE"

$CMD
CMD_EXIT_CODE=$?

# Create softlink for PID file to systemd expected location
SEEKDB_PID_FILE="$BASE_DIR/run/observer.pid"
if [ -f "$SEEKDB_PID_FILE" ] && [ "$SEEKDB_PID_FILE" != "$SYSTEMD_PID_FILE" ]; then
    # Create target directory if it doesn't exist
    mkdir -p "$(dirname "$SYSTEMD_PID_FILE")"
    # Remove existing link or file if exists
    rm -f "$SYSTEMD_PID_FILE"
    # Create softlink
    ln -s "$SEEKDB_PID_FILE" "$SYSTEMD_PID_FILE"
fi

# Check if command executed successfully
if [ $CMD_EXIT_CODE -eq 0 ]; then
    # Start obshell agent (ignore errors)
    echo "SeekDB started successfully, starting obshell agent..."
    if [ -f "/usr/bin/obshell" ]; then
        sleep 1
        /usr/bin/obshell agent start --seekdb --base-dir=$BASE_DIR || true
    else
        echo "Warning: /usr/bin/obshell not found, skipping obshell agent start"
    fi
else
    echo "SeekDB failed to start with exit code: $CMD_EXIT_CODE"
fi

exit $CMD_EXIT_CODE