#!/bin/sh
# -*- mode: sh; tab-width: 8; coding: utf-8-unix -*-
# https://unix.stackexchange.com/questions/293304/using-netcat-for-port-forwarding

prog=$( basename $0 .bash )
PREFIX=/usr/local
ROLE=proxy
. /usr/local/bin/usr_local_tput.bash || exit 2

if [ ! -d /run/tmp ] ; then
    sudo mkdir /run/tmp
    sudo chown 1777 /run/tmp
fi

[ -z "$MODE" ] && MODE=$(/usr/local/bin/proxy_ping_lib.bash proxy_ping_mode )
IP=`grep ' external$' /etc/hosts|sed -e 's/ .*//'`
retval=$?
if [ $retval -ne 0 ] || [ -z "$IP" ] ; then
    exit $retval
fi
 if [ "$MODE" = tor -o "$MODE" = gateway -o "$MODE" = selektor ] ; then
     socat -L/run/socat.lck udp-l:53,bind=$IP,fork,reuseaddr udp:127.0.0.1:9053 >/dev/null || \
	 WARN 53,bind=$IP in use
    for elt in 9050 9128 ; do
	netstat -nle4 | grep -q $IP:$elt && {
	    ERROR $IP:$elt already bound
	    continue # exit 1
	}
	DBUG socat -L/run/tmp/socat$elt.lck tcp-l:$elt,bind=${IP},fork,reuseaddr tcp:127.0.0.1:$elt
	socat -L/run/tmp/socat$elt.lck tcp-l:$elt,bind=${IP},fork,reuseaddr tcp:127.0.0.1:$elt &
    done
#else
#    WARN $MODE
#fi

