#!/bin/sh

init_variables() {
  COMMAND=${0##*/}

  PROXY_USER='proxyer'
  PORT='8080'

  MODE='regular'
  FRONTEND='tui'

  MITM_TOOL=
  MITM_OPTIONS="-p ${PORT}"
}

parse_command_line() {
  # shellcheck disable=SC2249
  while getopts f:t OPT; do
    case "${OPT}" in
      f) FRONTEND="${OPTARG}" ;;
      t) MODE='transparent' ;;
      ?) exit_error ;;
    esac
  done

  shift "$((OPTIND - 1))"

  MITM_OPTIONS="${MITM_OPTIONS} $*"
}

validate_command_line() {
  case "${FRONTEND}" in
    cli) MITM_TOOL='mitmdump' ;;
    tui) MITM_TOOL='mitmproxy' ;;
    web) MITM_TOOL='mitmweb' ;;
    *) exit_error "Invalid frontend '${FRONTEND}'" ;;
  esac
}

exit_error() {
  [ -z "$1" ] || echo "${COMMAND}: $1"
  exit 1
} >&2

proxy_transparent_enable() {
  doas sysctl -q -w net.ipv4.ip_forward=1
  doas sysctl -q -w net.ipv6.conf.all.forwarding=1
  doas sysctl -q -w net.ipv4.conf.all.send_redirects=0
  doas iptables -t nat -A OUTPUT -p tcp -m owner ! \
    --uid-owner "${PROXY_USER}" --dport 80 -j REDIRECT --to-port "${PORT}"
  doas iptables -t nat -A OUTPUT -p tcp -m owner ! \
    --uid-owner "${PROXY_USER}" --dport 443 -j REDIRECT --to-port "${PORT}"
  doas ip6tables -t nat -A OUTPUT -p tcp -m owner ! \
    --uid-owner "${PROXY_USER}" --dport 80 -j REDIRECT --to-port "${PORT}"
  doas ip6tables -t nat -A OUTPUT -p tcp -m owner ! \
    --uid-owner "${PROXY_USER}" --dport 443 -j REDIRECT --to-port "${PORT}"
}

proxy_transparent_disable() {
  doas sysctl -q -w net.ipv4.ip_forward=0
  doas sysctl -q -w net.ipv6.conf.all.forwarding=0
  doas sysctl -q -w net.ipv4.conf.all.send_redirects=1
  doas iptables -t nat -F
}

init_variables
parse_command_line "$@"
validate_command_line

# shellcheck disable=SC2086
if [ "${MODE}" = 'transparent' ]; then
  MITM_OPTIONS="${MITM_OPTIONS} --mode transparent --showhost --set block_global=false"

  if [ "${FRONTEND}" = 'web' ]; then
    # can't open browser from proxy user
    MITM_OPTIONS="${MITM_OPTIONS} --no-web-open-browser"
  fi

  proxy_transparent_enable
  doas -u "${PROXY_USER}" "${MITM_TOOL}" ${MITM_OPTIONS}
  proxy_transparent_disable
else
  "${MITM_TOOL}" ${MITM_OPTIONS}
fi
