#!/bin/bash

CONFIG_PATH=${1:-}

if [[ ${CURDIR:-} == "" ]]; then
    export CURDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
fi
source $CURDIR/set-env.sh

config_dir="$PROJECT_ROOT/scripts/stack/connectors-config"
script_config="$config_dir/config.yml"

if [ -f "$script_config" ]; then
    echo "config.yml already exists in $config_dir. Not overwriting."
    return 0
fi

is_example_config=false
if [[ "${CONFIG_PATH:-}" == "" ]]; then
    cp -n "$PROJECT_ROOT/config.yml.example" "$PROJECT_ROOT/config.yml"
    CONFIG_PATH="$PROJECT_ROOT/config.yml"
    is_example_config=true
fi

mkdir -p "$config_dir"
cp "$CONFIG_PATH" "$script_config"
echo "copied config from $CONFIG_PATH to $config_dir"

if [[ "$is_example_config" == true ]]; then
    export CONFIG_FILE="$script_config"
    sed_cmd="sed -i"
    if [[ "$MACHINE_OS" == "MacOS" || "$MACHINE_OS" == "FreeBSD" ]]; then
        sed_cmd="sed -i -e"
    fi
    $sed_cmd '/connectors:/s/^#//g' "$script_config"
    $sed_cmd '/elasticsearch.host/s/^#//g' "$script_config"
    $sed_cmd '/elasticsearch.username/s/^#//g' "$script_config"
    $sed_cmd '/elasticsearch.password/s/^#//g' "$script_config"

    if [[ "${ELASTIC_PASSWORD:-}" != "" ]]; then
        esc_pass=$(printf '%s' "$ELASTIC_PASSWORD" | sed 's/[&|\\]/\\&/g')
        $sed_cmd "/^elasticsearch\.password:/s|:.*|: ${esc_pass}|" "$script_config";
    fi
fi
