# -*- mode: shell-script -*-


CONFIG_DIR="$SERVICE_CONFIGSTORE"/etc/etherpad
ORIG_CONFIG_FILE="$CONFIG_DIR/settings.json.orig"

etherpad:ensure-orig-json-exists() {
    if ! [ -e "$ORIG_CONFIG_FILE" ]; then
        mkdir -p "${ORIG_CONFIG_FILE%/*}" || return 1
        ## Remove comments from container file and copy it in
        ## configstore
        if out=$(docker run --rm --entrypoint bash "$DOCKER_BASE_IMAGE" \
                        -c "npm install mjson && node_modules/.bin/mjson.js < settings.json"); then
            ## XXXvlab: output from mjson.js is still minified in my local install
            ## lets keep this code if necessary later.
            # if ! echo "$out" | jq . > "$ORIG_CONFIG_FILE"; then
            #     err "Jq failed with output from container."
            #     rm -fv "$ORIG_CONFIG_FILE"
            #     return 1
            # fi
            echo "$out" > "$ORIG_CONFIG_FILE"
        else
            err "Could not out-source clean 'setting.json' from container."
            return 1
        fi
    fi
}


etherpad:api:init() {
    container_network_ip=$(get_healthy_container_ip_for_service "$SERVICE_NAME" 9001 4) || {
        echo "  Please ensure that ${DARKYELLOW}${SERVICE_NAME}${NORMAL} is running before using '$exname'." >&2
        return 1
    }

    container_ip=${container_network_ip##*:}
    container_network=${container_network_ip%%:*}

    export ETHERPAD_DOCKER_OPTS=(--network "$container_network")

    if ! API_KEY=$(cat "$SERVICE_DATASTORE/var/lib/etherpad/APIKEY.txt"); then
        err "Can't find API KEY for ${DARKYELLOW}${SERVICE_NAME}${NORMAL}."
        return 1
    fi

    export DEFAULT_CURL_IMAGE=${DEFAULT_CURL_IMAGE:-docker.0k.io/curl}
    export ETHERPAD_HOST="http://${container_ip}:9001"

    if ! out=$(etherpad:curl api/openapi.json); then
        err "Couldn't get API description from ${DARKYELLOW}${SERVICE_NAME}${NORMAL}."
        return 1
    fi

    if ! api_version=$(e "$out" | jq -r '.info.version'); then
        err "Couldn't get version information from ${DARKYELLOW}${SERVICE_NAME}${NORMAL} API's description."
        # echo "$out" | prefix "  | " >&2
        return 1
    fi

    export ETHERPAD_API_BASE_PATH="api/${api_version}"
}

etherpad:curl() {
    local path="$1" cmd
    shift
    cmd=(
        docker run --rm "${ETHERPAD_DOCKER_OPTS[@]}"
        "$DEFAULT_CURL_IMAGE"
        -sS
        "$@"
        "${ETHERPAD_HOST}/$path"
    )

    # debug "Launching: ${cmd[@]}"
    "${cmd[@]}"
}

etherpad:api() {
    local method="$1" code out
    shift

    if [ -z "$ETHERPAD_API_BASE_PATH" ]; then
        etherpad:api:init
    fi

    if ! out=$(
            etherpad:curl "${ETHERPAD_API_BASE_PATH}/$method" -X POST -d "apikey=${API_KEY}" "$@"
         ); then
        err "Couldn't query API ${WHITE}$method${NORMAL} from ${DARKYELLOW}${SERVICE_NAME}${NORMAL}."
        return 1
    fi
    if ! code=$(e "$out" | jq -r ".code"); then
        err "Unexpected response format from call to ${WHITE}$method${NORMAL} " \
            "API endpoint for ${DARKYELLOW}${SERVICE_NAME}${NORMAL}."
        # echo "$out" | prefix "  | " >&2
        exit 1
    fi
    if [[ "$code" != "0" ]]; then
        if ! message=$(e "$out" | jq -r ".message"); then
            err "Unexpected response format from call to ${WHITE}$method${NORMAL} " \
                "API endpoint for ${DARKYELLOW}${SERVICE_NAME}${NORMAL}."
            # echo "$out" | prefix "  | " >&2
            exit 1
        fi
        err "${WHITE}$method${NORMAL}: $message"
        # echo "$out" | prefix "  | " >&2
        exit 1
    fi

    e "$out" | jq '.data'
}