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

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

# Check vpn is working
if [ -f /currentip ]; then

  # Get vpn ip
  if bashio::config.true 'openvpn_alt_mode'; then
    curl -s ipecho.net/plain > /vpnip
  else
    curl -s ipecho.net/plain --interface tun0 > /vpnip
  fi
  
  # Verify ip has changed
  if [[ "$(cat /vpnip)" = "$(cat /currentip)" ]]; then
    bashio::log.fatal "VPN is not properly configured. Your ip is exposed. Please fix this, or do not use the vpn alt mode"
    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 $(curl -s ipecho.net/plain), based in country : $COUNTRY"
  rm /vpnip
  rm /currentip

fi

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

exec nginx
