#!/command/with-contenv /bin/bash
# shellcheck shell=bash

# shellcheck disable=SC1091,SC1090

SCRIPT_ROOT=/etc/s6-overlay/scripts
source "$SCRIPT_ROOT/base.sh"
source "$GPUSTACK_GATEWAY_CONFIG"
source "$SCRIPT_ROOT/default-variables.sh"

set -e

exec 2>&1

if [ -z "$EMBEDDED_KUBECONFIG_PATH" ]; then
    echo "  Missing required variable EMBEDDED_KUBECONFIG_PATH in apiserver configuration."
    exit 255
fi
createDir "$APISERVER_DATA_DIR"

# prepare default data
cp -rn /etc/gpustack/data/defaultConfig/* "${APISERVER_DATA_DIR}/"

# prepare mesh config
MESH_CONFIG_DIR='/etc/istio/config'
createDir "$MESH_CONFIG_DIR"
HIGRESS_CONFIG_FILE="${APISERVER_DATA_DIR}/configmaps/higress-config.yaml"
MESH_CONFIG_FILES=$(yq -r '.data | keys | .[]' "$HIGRESS_CONFIG_FILE")
if [ -z "$MESH_CONFIG_FILES" ]; then
    echo "  Missing required files in higress-config ConfigMap."
    exit 255
fi
IFS=$'\n'
for MESH_CONFIG_FILE in $MESH_CONFIG_FILES; do
    if [ -z "$MESH_CONFIG_FILE" ] || [ "$MESH_CONFIG_FILE" == "higress" ]; then
        continue
    fi
    yq -r ".data.$MESH_CONFIG_FILE" "$HIGRESS_CONFIG_FILE" > "$MESH_CONFIG_DIR/$MESH_CONFIG_FILE"
done

echo "[INFO] Starting Higress APIServer."
exec s6-notifyoncheck \
    -d -w 5000 -n 10 -s 3000 \
    -- \
    /usr/local/bin/apiserver \
    --bind-address 127.0.0.1 \
    --secure-port "${APISERVER_PORT}" \
    --storage file \
    --file-root-dir "${APISERVER_DATA_DIR}" \
    --cert-dir /tmp
