#!/usr/bin/env bash

# Allows easy manipulation of the proxy variables

function proxy_set_help {
    echo "Usage: $0 set ADDRESS"
    echo
    echo "Arguments:"
    echo "    ADDRESS  Address of the proxy"
    echo
    echo "Examples:"
    echo '    eval "$(proxy set http://proxy.mycompany.com:3128/)"'
    return 0
}

function proxy_set {
    if [ -z  $1 ]; then
        proxy_set_help
        return 1
    fi
    echo "export http_proxy='$1'"
    echo "export https_proxy='$1'"
    echo "export ftp_proxy='$1'"
    echo "export rsync_proxy='$1'"
    exit 0
}

function proxy_setup_help {
    echo "Usage: $0 setup"
    echo
    echo "Examples:"
    echo "    proxy_set # Then eval the output"
    return 0
}
function proxy_setup {
    export no_proxy="localhost,127.0.0.1,localaddress,.localdomain.com"

    if (( $# > 0 )); then
        valid=$(echo $@ | sed -n 's/\([0-9]\{1,3\}.\)\{4\}:\([0-9]\+\)/&/p')
        if [[ $valid != $@ ]]; then
            >&2 echo "Invalid address"
            return 1
        fi
        proxy_set "http://$1/"
        return 0
    fi

    echo -n "User: "; read username
    if [[ $username != "" ]]; then
        echo -n "Password: "
        read -es password
        local pre="$username:$password@"
    fi

    echo -n "Server: "; read server
    echo -n "Port: "; read port
    proxy_set "http://$pre$server:$port/"
    return 0
}

function proxy_off_help {
    echo "Usage: $0 off"
    echo
    echo "Examples:"
    echo '    eval $(proxy off)'
    return 0
}
function proxy_off {
    echo 'unset http_proxy'
    echo 'unset https_proxy'
    echo 'unset ftp_proxy'
    echo 'unset rsync_proxy'
    return 0
}

function proxy_help {
    command="$1"
    if [ -n "$command" ]; then
        if type "proxy_${command}_help" &> /dev/null; then
            shift
            "proxy_${command}_help" "$@"
            return $?
        fi
    fi
    echo "Usage: $0 COMMAND"
    echo
    echo "Commands:"
    echo "    setup    Interactively setup proxy"
    echo "    set      Set proxy from address"
    echo "    off      Turn off proxy"
    echo "    help     Get help with commands"
    return 0
}

# MAIN
command="$1"
shift
if type "proxy_$command" &> /dev/null; then
    "proxy_$command" "$@"
else
    proxy_help
fi