Kyle-Falconer
6/13/2016 - 11:01 PM

Proxy Autostart/auto-configure shell script for Mac OS 10.11.5

Proxy Autostart/auto-configure shell script for Mac OS 10.11.5

#!/bin/sh

# Proxy Autostart/auto-configure for Mac OS 10.11.5
# written by Kyle Falconer <Kyle.Falconer@vta.org> June 2016
#
# cntlm was setup using the instructions found at:
#    http://blog.hoachuck.biz/blog/2013/03/21/howto-set-cntlm-on-mac-os-x/
#
# cntlm autostarts using launchctl 
# see the plist at
#    ~/Library/LaunchAgents/org.vta.cntlm.daemon.plist


WIFI_INTERFACE="en0"
ETHERNET_INTERFACE="en4"
INTRANET_ADDR="thehub.vta.org"
INTERNET_ADDR="google.com"

COLOR_RED="\033[91m"
COLOR_GREEN="\033[92m"
COLOR_RESET="\033[0m"


ifactive () {
    if [ "`ifconfig | sed -n '/^'$1'/,/^[a-z]/ s/.*status: \(.*\)$/\1/p'`" = "active" ]; then
        echo "true"
    else
        echo "false"
    fi
}

boolping () {
    ping -oc 2 $1 > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "true"
    else
        echo "false"
    fi
}

ETHERNET_UP=$(ifactive $ETHERNET_INTERFACE)
WIFI_UP=$(ifactive $WIFI_INTERFACE)

INTERNET_UP=$(boolping $INTERNET_ADDR)
INTRANET_UP=$(boolping $INTRANET_ADDR)


# The proxy should be enabled if on the intranet over ethernet

if [ $INTRANET_UP = "true" -a $ETHERNET_UP = "true" ]; then
    # echo "setting up proxy settings"
    # standard env vars
    export http_proxy=http://localhost:3128
    export https_proxy=https://localhost:3128
    export all_proxy=http://localhost:3128

    # application-specific
    alias curl="curl -x ${http_proxy}"
    npm config set proxy ${http_proxy}
    npm config set registry http://registry.npmjs.org/
    git config --global http.proxy ${http_proxy} > /dev/null 2>&1
    PROXY_STATUS="true"
else
    # echo "turning off proxy settings"
    # standard env vars
    unset http_proxy
    unset https_proxy
    unset all_proxy
    
    # application-specific
    npm config set registry https://registry.npmjs.org/
    npm config delete proxy
    npm config delete https-proxy
    git config --global --unset http.proxy > /dev/null 2>&1
    PROXY_STATUS="false"
fi

ETHERNET_STATUS=$([ $ETHERNET_UP = "true" ] && echo $COLOR_GREEN"up"$COLOR_RESET || echo $COLOR_RED"down"$COLOR_RESET )
WIFI_STATUS=$([ $WIFI_UP = "true" ] && echo $COLOR_GREEN"up"$COLOR_RESET || echo $COLOR_RED"down"$COLOR_RESET )
INTRANET_STATUS=$([ $INTRANET_UP = "true" ] && echo $COLOR_GREEN"up"$COLOR_RESET || echo $COLOR_RED"down"$COLOR_RESET )
INTERNET_STATUS=$([ $INTERNET_UP = "true" ] && echo $COLOR_GREEN"up"$COLOR_RESET || echo $COLOR_RED"down"$COLOR_RESET )
PROXY_STATUS=$([ $PROXY_STATUS = "true" ] && echo $COLOR_GREEN"enabled"$COLOR_RESET || echo $COLOR_RED"disabled"$COLOR_RESET )
printf  'Ethernet: %s, WiFi: %s, intranet: %s, internet: %s, proxy: %s\n' "$ETHERNET_STATUS" "$WIFI_STATUS" "$INTRANET_STATUS" "$INTERNET_STATUS" "$PROXY_STATUS"