#!/usr/bin/env bash
set -e

function with_set_x() {
    set -x
    "$@"
    {
        ec=$?
        set +x
        return $ec
    } 2>/dev/null
}

ssh_cmd='ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null'
args=()
while [[ $# -gt 0 ]]; do
    arg=$1
    shift
    case "$arg" in
    -v)
        ssh_cmd+='-v'
        ;;
    --copy-id)
        ssh_copy_id=true
        continue
        ;;
    -6)
        ipv6_only=true
        continue
        ;;
    --sshuttle-bin=*)
        sshuttle_bin="${arg#*=}"
        continue
        ;;
    -*) ;;
    *)
        if [[ -z "$node" ]]; then
            node=$arg
            continue
        fi
        ;;
    esac
    args+=("$arg")
done

port="2222"
user="test:test"

if [[ $node == node-* ]]; then
    host=$("$(dirname "$0")/test-bed" get-ip "$node")
    index=${node#node-}
    if [[ $ipv6_only == true ]]; then
        args+=("2001:0DB8::/112")
    else
        args+=("10.55.$index.0/24")
    fi
else
    host=$node
fi

if [[ "${#args[@]}" -ne 0  && "${args[$((${#args[@]} - 1))]}" != *.* && "${args[$((${#args[@]} - 1))]}" != *:* ]]; then
    echo "No subnet specified. Using -N" >&2
    args+=('-N')
fi

if ! command -v sshpass >/dev/null; then
    echo "sshpass is not found. You might have to manually enter ssh password: 'test'" >&2
    user=${user%:*}
fi

if [[ $ssh_copy_id == true ]]; then
    echo "Trying to make it passwordless" >&2
    with_set_x ssh-copy-id -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -p "$port" "$user@$host"
fi

if [[ -z $sshuttle_bin || "$sshuttle_bin" == dev ]]; then
    cd "$(dirname "$0")/.."
    export PYTHONPATH="."
    sshuttle_bin="./run"
fi

set -x
$sshuttle_bin --version
exec "${sshuttle_bin}" -r "$user@$host:$port" --ssh-cmd "$ssh_cmd" "${args[@]}"