#!/bin/bash
# -*- mode: sh; fill-column: 75; tab-width: 8; coding: utf-8-unix -*-

PREFIX=/usr/local
ROLE=proxy

. /usr/local/bin/usr_local_base.bash || exit 2

if [ "$#" -eq 1 -a "$1" = '--version' ] ; then
    exec /usr/bin/dirmngr.bin --version
    return 0
fi

# echo "DEBUG: $0 GNUPGHOME=$GNUPGHOME $*" >> /tmp/$$.out
PROXY_GPG_KEYSERVER=keys.openpgp.org

[ -f /usr/local/etc/testforge/testforge.bash ] && . /usr/local/etc/testforge/testforge.bash >/dev/null
[ -z "$PROXY_GPG_KEYERVER_URL" ] && PROXY_GPG_KEYERVER_URL=hkps://$PROXY_GPG_KEYSERVER

# ONLY disabling  on  the command line or
[ -e /proc/sys/net/ipv6/conf/default/disable_ipv6 ] && \
  [ `cat /proc/sys/net/ipv6/conf/default/disable_ipv6` -eq 0 ] && \
  echo 1 > /proc/sys/net/ipv6/conf/default/disable_ipv6

PROXY_WLAN=$( /usr/local/bin/proxy_ping_lib.bash proxy_set_if ) # || return 1$?
if [ -n "$PROXY_WLAN" ] ; then
    wlan7=$PROXY_WLAN

    [ -e /proc/sys/net/ipv6/conf/$wlan7/disable_ipv6 ] && \
	[ `cat /proc/sys/net/ipv6/conf/$wlan7/disable_ipv6` -eq 0 ] && \
	echo 1 > /proc/sys/net/ipv6/conf/$wlan7/disable_ipv6
fi

grep -q "^wlan[1-9][ 	]00000000" /proc/net/route || { ERROR no route ; exit 1; }
[ ! -x /usr/bin/netstat ] || \
  netstat -nlp | grep -q 127.0.0.1:53 || { ERROR no nameserver ; exit 4; }

[ -z "$USER" ] && USER=$(id -un )
if [ $USER = root ] ; then
    [ -x /usr/bin/dirmngr -a ! -x /usr/bin/dirmngr.bin ] && \
	mv /usr/bin/dirmngr /usr/bin/dirmngr.bin
    [ -x /usr/bin/dirmngr.bin -a ! -x /usr/bin/dirmngr ] && \
	ln -s /usr/local/bin/proxy_dirmngr.bash /usr/bin/dirmngr
fi

[ ! -x /usr/bin/dirmngr -o ! -x /usr/bin/dirmngr.bin ] && exit 2
[ -f /etc/dirmngr/dirmngr.conf ] || exit 3

# This is not enough: --disable-ipv6
# --keyserver hkps://keys.gentoo.org is required
# --http-proxy http://127.0.0.1:3128
# --keyserver $PROXY_GPG_KEYERVER_URL
# --no-use-tor is REQUIRED if you are running tor
# EVEN IF YOU DOT USE use-tor - silent dns failure

exec /usr/bin/dirmngr.bin --server -vvv --debug-all \
	--options /etc/dirmngr/dirmngr.conf \
       --nameserver 127.0.0.1 \
       --disable-ipv6 \
       --disable-ldap \
	--no-use-tor \
	--log-file /var/log/dirmngr.log --debug-level 4 \
	"$@"
