#!/bin/bash 

DEFAULTPORTS=(80 22)
IFCONF=/sbin/ifconfig
OUTPUTBLOCK=4
SCREENNAME=tunneler

if [ "$#" -lt 4 ]; then
cat << EOF

Help SSH tunnel creation from localhost
Usage: $0 -h <user@remotehost> -p <first free port at remotehost> [-l <space separated list of forwarded local ports>] [-i <space separated list of forwarded local interfaces>] [-f <flags>]
Flags:
    s - create sessions inside screen
Example: $0 -h juks@juks.alkohol.ee -p 8081 -l 80 -f s
Dependencies: ifconfig, whiptail, ssh, screen

EOF
exit
fi

declare -A clargs
while [[ $# > 1 ]]; do
    key="$1"
    key=${key:1}
    clargs["$key"]="$2"
    shift # past argument or value
done

flags=""
if [ ${clargs[f]+1} ]; then
    flags="${clargs[f]}"
fi

ifaces=()
declare -A ips
while read ifacerow; do
    IFS=' ' read -a ifacepieces <<< "${ifacerow}"
    iprow=$($IFCONF "${ifacepieces[0]}" | grep 'inet addr:' )
    if [ ! -z "$iprow" ]; then
        ifaces=("${ifaces[@]}" "${ifacepieces[0]}")
        IFS=': ' read -a ippieces <<< "$iprow"
        ips["${ifacepieces[0]}"]="${ippieces[2]}"
    fi
done < <($IFCONF | grep 'Link encap:Ethernet')

if [ ${#ifaces[@]} -lt 1 ]; then
    echo "Localhost isn't connected to internet!"
    exit
fi

whiptailresult=()
function whiptailer()
{
    declare -a argAry=("${!1}")
    choose=""
    for i in "${!argAry[@]}"; do
        choose="$choose ${argAry[$i]} on"
    done
    txt="$2"
    height=$((7 + ${#argAry[@]}))
    length=$((4 + ${#txt}))
    chosen=$(whiptail --checklist "$txt" $height $length ${#argAry[@]} $choose --noitem 3>&1 1>&2 2>&3)
    if [ ! -z "$chosen" ]; then
        argAry=()
        IFS=' "' read -a pieces <<< "${chosen}"
        for i in "${!pieces[@]}"; do
            if [ ! -z ${pieces[$i]} ]; then
                argAry=("${argAry[@]}" "${pieces[$i]}")
            fi
        done
    fi
    whiptailresult=("${argAry[@]}")
}

if [ ${clargs[i]+1} ]; then
    IFS=' ' read -a ifaces <<< "${clargs[i]}"
else
    if [ ${#ifaces[@]} -gt 1 ]; then
        whiptailer ifaces[@] "Choose local interfaces"
        ifaces=("${whiptailresult[@]}")
    fi
fi

if [ ${clargs[l]+1} ]; then
    IFS=' ' read -a DEFAULTPORTS <<< "${clargs[l]}"
else
    whiptailer DEFAULTPORTS[@] "Choose local ports which will be forwarded"
    DEFAULTPORTS=("${whiptailresult[@]}")
fi

port=${clargs[p]}
output=()
tabno=0
screencmds=("screen -S ${SCREENNAME} -X quit")
for i in "${!ifaces[@]}"; do
    for j in "${!DEFAULTPORTS[@]}"; do
        iface="${ifaces[$i]}"
        output=("${output[@]}" "##### ${port} ############################################################")
        output=("${output[@]}" "ssh ${clargs[h]} -R ${port}:${ips[${ifaces[$i]}]}:${DEFAULTPORTS[$j]}")
        output=("${output[@]}" "# log in and paste to command line: ")
        output=("${output[@]}" "while true ; do d=\$(date '+%Y%m%d %H%M ${ifaces[$i]}:${DEFAULTPORTS[$j]}>${clargs[h]}:${port}') ;  echo -en \"\r\$d\"; sleep 60 ; done")
        screencmd="$0 -h ${clargs[h]} -p ${port} -l ${DEFAULTPORTS[$j]} -i ${ifaces[$i]} -f S"
        if [ "$tabno" -lt 1 ]; then
            screencmds=("${screencmds[@]}" "screen -AdmS ${SCREENNAME} -t tab0 ${screencmd}")
        else
            screencmds=("${screencmds[@]}" "screen -S ${SCREENNAME} -X screen -t tab${tabno} ${screencmd}")
        fi
        port=$((1 + ${port}))
        tabno=$((1 + ${tabno}))
    done
done
screencmds=("${screencmds[@]}" "screen -r ${SCREENNAME}")
simple_output=true

if [[ $flags == *"s"* ]]; then
    for i in "${!screencmds[@]}"; do
        eval ${screencmds[$i]}
    done
    simple_output=false
fi

if [[ $flags == *"S"* ]]; then
    echo ${output[2]}
    echo ${output[3]}
    eval ${output[1]}
    simple_output=false
fi


if [ "$simple_output" = true ] ; then
    if [ ${#output[@]} -gt $OUTPUTBLOCK ]; then
        echo ""
        echo "----- COPY COMMANDS: BEGIN --------------------------------------------"
        for i in "${!output[@]}"; do
            if [ $i -lt $OUTPUTBLOCK ]; then
                continue
            fi
            echo ${output[$i]}
        done
        echo "----- COPY COMMANDS: END ----------------------------------------------"
    fi
    echo ""
    echo ${output[2]}
    echo ${output[3]}
    eval ${output[1]}
fi