#!/usr/bin/with-contenv bashio
# shellcheck shell=bash
set -e
# ==============================================================================

# Set variables
slug=jackett
port=9117
CONFIG_LOCATION=/config/addons_config/Jackett/ServerConfig.json

# Wait for Jackett to become available
bashio::net.wait_for "$port" localhost 900

# Ensure BasePathOverride is set for ingress
if [ -f "$CONFIG_LOCATION" ] && ! bashio::config.true "ingress_disabled"; then
    if ! grep -q "\"BasePathOverride\"[[:space:]]*:[[:space:]]*\"${slug}\"" "$CONFIG_LOCATION"; then
        bashio::log.warning "BasePathOverride not set properly, restarting"
        sed -i -E "s/\"BasePathOverride\"[[:space:]]*:[[:space:]]*\"[^\"]*\"/\"BasePathOverride\": \"${slug}\"/" "$CONFIG_LOCATION"
        bashio::addon.restart
    fi
fi

bashio::log.info "Starting NGinx..."
exec nginx
