#!/bin/bash
# -*-mode: sh; tab-width: 8; coding: utf-8-unix -*-
## /usr/local/bin/proxy_whonix_tor_start.bash

ROLE=proxy
[ -z "$prog" ] && prog=$( basename $0 .bash )
[ -z "$PRIV_TOR_OWNER" ] && grep -q ^debian-tor /etc/passwd && PRIV_TOR_OWNER=debian-tor

## host_tor_verify_config
. /usr/local/bin/usr_local_tput.bash || exit 3
host_tor_verify_config () {
    # tor --verify-config # || exit 2$?
    su -c 'tor --verify-config' -s /bin/sh $PRIV_TOR_OWNER \
	| grep -v 'notice\|DisableNetwork'
    # || exit 2
    return 0
}

tor_grep_log () {
    local log

    [ -f /run/tor/log ] && log=/run/tor/log || log=/tmp/tor.log
    [ -f $log ] || { WARN $prog $log not found ; return 1 ; }

    INFO grep % $log
    grep % $log | grep -v 5%

    return 0
}

## host_tor_is_running
host_tor_is_running () {
    local retval

    retval=0
    if netstat -nlp4 2>&1| grep ':90.*/tor' ; then
	DBUG $prog tor is already running
	retval=2
    elif ps ax | grep -v grep | grep "su -c tor -s /bin/sh $PRIV_TOR_OWNER" ; then
	DBUG $prog tor is already running
	retval=3
    elif ls -l /run/tor/socket 2>/dev/null ; then
	DBUG $prog tor is already running
	retval=4
    fi
    tor_grep_log
    return $retval
}

## host_tor_start
host_tor_start () {
    #su -c '/etc/init.d/tor stop' -s /bin/sh $PRIV_TOR_OWNER
    #sleep 5

    [ -d /run/tor/  ] && rm -f /run/tor/* || mkdir /run/tor
    # systemd overrides these
    chown $PRIV_TOR_OWNER.$PRIV_TOR_OWNER /run/tor
    chmod 2750  /run/tor/

    gateway_tor_stop
    # systemctl daemon-reload
    rm -f /run/tor/log.err /tmp/log.err
    rm -f /run/tor/log /tmp/log.log
    rm -f /run/tor/tor.pid /tmp/log.pid


    INFO starting tor - see /tmp/tor.err /tmp/tor.log

    if false ; then
    su -c '/etc/init.d/tor start' -s /bin/sh $PRIV_TOR_OWNER
    netstat -nlp -t inet | grep "$IP:9128" || systemctl --no-pager restart tor@default || return 4$?
else
    su -c 'tor' -s /bin/sh $debian 2>/tmp/tor.err >/tmp/tor.log &
    echo -n $! >/tmp/tor.pid
fi
    sleep 15

    return 0
}

## host_tor_stop
host_tor_stop () {
    local debian

    [ -s /tmp/tor.pid ] && \
	DBUG $prog kill $( cat /tmp/tor.pid ) && \
	kill $( cat /tmp/tor.pid ) 2>/dev/null && \
	rm /tmp/tor.pid
    rm -f /tmp/tor.log /tmp/tor.err
    debian=$PRIV_TOR_OWNER
    pkill -u $debian
    [ -s /tmp/tog.pid ] && \
	kill $( cat /tmp/tog.pid ) 2>/dev/null \
	&& rm /tmp/tog.pid
    # echo 1|sudo dd of=/proc/sys/net/ipv4/tcp_tw_reuse
    return 0
}

PROXY_ExcludeNodes="{gb},{ca}"

## proxy_tor_torrc_update
proxy_tor_torrc_update () {
    local file IP
    file=$1
    IP=$2
    grep -q "SocksPort $IP:9050" $file || \
	echo "SocksPort $IP:9050" >> $file
    grep -q "DNSPort $IP:9053" $file || \
	echo "DNSPort $IP:9053" >> $file
    if false ; then
	grep -q "TransPort $IP:9040" $file || \
	    echo "TransPort $IP:9040 IsolateClientAddr IsolateClientProtocol IsolateDestAddr IsolateDestPort" >> $file
    fi
    grep -q "HTTPTunnelPort $IP:9128" $file || \
	echo "HTTPTunnelPort $IP:9128 IsolateDestAddr" >> $file
    return 0
}


export TOR_LOG="/var/log/tor/log"
export TOR_DIR=/var/lib/tor/data

cmd_item_list=(
"--has-consensus"
"--current-time-in-valid-range"
"--show-valid-after"
"--show-valid-until"
"--show-middle-range"
)

#"--tor-cert-lifetime-invalid"
#"--tor-cert-valid-after"

## proxy_tor_test_ntp
proxy_tor_test_ntp () {
    /usr/local/bin/proxy_ping_test.bash ntp
    return $?
}

## proxy_tor_test_anondate
proxy_tor_test_anondate () {
    local cmd_item outout exit_code

for cmd_item in ${cmd_item_list[@]} ; do
   output="$( /usr/local/lib/helper-scripts/anondate $cmd_item $@ )"
   exit_code="$?"
   if [ $exit_code -eq 0 ] ; then
       INFO "/usr/local/lib/helper-scripts/anondate $cmd_item $@"
       echo "output: $output"
    else
       echo "WARN: /usr/local/lib/helper-scripts/anondate $cmd_item $@"
       echo -n "exit_code: $exit_code "
       echo "output: $output"
      fi
done
    return 0
}

host_tor_status () {
    [ -f /tmp/tor.pid ] && \
	[ $( wc -c /tmp/tor.pid|sed -e 's/ .*//' ) -le 1 ] && \
	rm /tmp/tor.pid

    if [ -f /tmp/tor.pid ]; then
	ps -p "$( cat /tmp/tor.pid )"
      elif [ -f /run/tor/tor.pid ] ; then
	ps -p "$( cat /run/tor/tor.pid )"
      else
	WARN $prog no /tmp/tor.pid or /run/tor/tor.pid
      fi

    [ ! -f /usr/local/src/helper-scripts/tor_bootstrap_check.py ] || \
      python3 /usr/local/src/helper-scripts/tor_bootstrap_check.py \
	|| return 1

    debian=$PRIV_TOR_OWNER
    INFO $prog $debian processes:
    ps -g $debian

    guest_qemu_status || return 2$?
    tor_start_not_running && return 3$?

    [ ! -f /usr/local/src/helper-scripts/tor_circuit_established_check.py ] || \
      a=$( python3 /usr/local/src/helper-scripts/tor_circuit_established_check.py ) \
	|| return 4
      [ "$a" = "1" ]|| { echo "WARN: $prog tor_circuit_established_check != 1" ;
                         return 5
    }

    return 0
}

## proxy_tor_torrc_exclude
proxy_tor_torrc_exclude () {
    local file
    [ $# -eq 0 ] && file=$1 || file=/etc/tor/torrc
    [ -n "$file" ] || return 1
    [ -f "$file" ] || return 2
    [ -n "$PROXY_ExcludeNodes" ] || return 3
    grep -q "ExcludeNodes.*$PROXY_ExcludeNodes" "$file" && return 0
    if grep -q "ExcludeNodes" $file ; then
       sed -e "s@ExcludeNodes.*@ExcludeNodes ${PROXY_ExcludeNodes}@" -i $file
      else
        echo "ExcludeNodes $PROXY_ExcludeNodes" >> $file
     fi

    return 0
}

base=proxy_tor_lib
if [ -x /usr/bin/basename ] && [ $( /usr/bin/basename -- $0 ) = $base'.bash' -o $( basename -- $0 ) = $base'.sh' ] ; then
    [ "$#" -eq 0 ] && exit 0
    [ "$#" -eq 1 ] && [ "$1" = '-h' -o "$1" = '--help' ] && echo USAGE: $0 && grep '^[a-z].*()\|^## ' $0 | sed -e 's/().*//'|sort && exit 0
    eval "$@"
    exit $?
  fi

