#!/bin/bash

if [ "$(whoami)" != "root" ]; then
  exit 2
fi

# Remover alias IP e regras NAT do loopback installer
ALIAS_STATE_FILE="/usr/local/etc/warsaw/.lo_alias_ip"
IPTABLES=""
if [ -x /sbin/iptables ]; then
  IPTABLES=/sbin/iptables
elif [ -x /usr/sbin/iptables ]; then
  IPTABLES=/usr/sbin/iptables
fi
CANDIDATE=""
if [ -f "$ALIAS_STATE_FILE" ]; then
  CANDIDATE=$(head -1 "$ALIAS_STATE_FILE" 2>/dev/null)
fi
if [ -z "$CANDIDATE" ]; then
  CANDIDATE=$(ip -4 addr show dev lo 2>/dev/null | awk '/inet / && !/127\./{gsub(/\/.*/, "", $2); print $2; exit}')
fi
if [ -n "$CANDIDATE" ] && ! echo "$CANDIDATE" | grep -qE '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'; then
  CANDIDATE=""
fi
ALIAS_IP=""
if [ -n "$CANDIDATE" ] && [ -n "$IPTABLES" ]; then
  if "$IPTABLES" -t nat -C OUTPUT -p tcp -d "$CANDIDATE" --dport 443 -j DNAT --to-destination 127.0.0.1:30900 2>/dev/null; then
    ALIAS_IP="$CANDIDATE"
  fi
fi
if [ -n "$ALIAS_IP" ]; then
  for CHAIN in PREROUTING OUTPUT; do
    while "$IPTABLES" -t nat -C "$CHAIN" -p tcp -d "$ALIAS_IP" --dport 443 -j DNAT --to-destination 127.0.0.1:30900 2>/dev/null; do
      "$IPTABLES" -t nat -D "$CHAIN" -p tcp -d "$ALIAS_IP" --dport 443 -j DNAT --to-destination 127.0.0.1:30900 2>/dev/null || break
    done
  done
  ip addr del "$ALIAS_IP"/32 dev lo 2>/dev/null || :
fi
rm -f "$ALIAS_STATE_FILE" 2>/dev/null || :

rm -rf /usr/local/bin/warsaw
rm -rf /usr/local/lib/warsaw
rm -rf /usr/local/etc/warsaw
rm -rf /usr/local/share/fonts/truetype/dbldwrsw.ttf
