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

# Wait for transmission to become available
bashio::net.wait_for 8080 localhost 900

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

if [[ "$(bashio::config 'VPN_ENABLED')" == "yes" ]]; then
  exec nginx & \
  while true; do
    # Get vpn ip
    curl -s ipecho.net/plain --interface tun0 > /vpnip

    # Verify ip has changed
    if [[ "$(cat /vpnip)" = "$(cat /currentip)" ]]; then
      bashio::log.fatal "VPN is not properly configured. Your ip is exposed."
      bashio::exit.nok
    fi

    # Get ip location
    COUNTRY=$(curl -s https://ipinfo.io/$(cat /vpnip) | grep country -i -m 1 | cut -d ':' -f 2 |xargs | awk 'gsub(/,$/,x)' || true)

    # Inform by message
    bashio::log.info "VPN is up and running with ip $(cat /vpnip), based in country : $COUNTRY"

    # Check every 15m
    sleep 30m

    true
  done
else
  exec nginx
fi
