#!/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"
    return 0
}

function proxy_set {
    if [ -z  $1 ]; then
        proxy_set_help
        return 1
    fi
    export http_proxy=$1
    export https_proxy=$1
    export ftp_proxy=$1
    export rsync_proxy=$1
    echo "Proxy changed"
    exit 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 {
    unset http_proxy
    unset https_proxy
    unset ftp_proxy
    unset rsync_proxy
    echo -e "Proxy removed"
    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