#!/usr/bin/env bash
#
# Copyright (c) 2008-2011 VMware, Inc.  All rights reserved.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# 

#
# Update the proxy configuration
#
# $1 == Proxy server name, or NONE
# $2 == Proxy server port
#

VAMI_BIN=/opt/vmware/share/vami
. $VAMI_BIN/vami_common

export TEXTDOMAINDIR=/opt/vmware/lib/locale
export TEXTDOMAIN=vami_set_proxy

ENV_FILE=/etc/environment
SYSCFG_PROXY="/etc/sysconfig/proxy"

if [ $# -lt 2 -a "$1" != "NONE" ]
then
    echo `gettext "Usage:"` $0 'NONE|[proxy_server proxy_port]'
    exit 1
fi
    
#
# If proxy server is NONE, set up to remove any existing proxy config
#
if [ "$1" = "NONE" ]
then
    install_proxy=FALSE
    vami_log notice New proxy parameters requested: Remove Proxy
else
    install_proxy=TRUE
    proxy_spec=http://${1}:${2}
    vami_log notice New proxy parameters requested: $1:$2
fi

cp $ENV_FILE ${ENV_FILE}.orig
grep -v http_proxy= < ${ENV_FILE}.orig > $ENV_FILE

if [ $install_proxy = TRUE ]
then
    echo "http_proxy=$proxy_spec" >> $ENV_FILE

    if [ -f $SYSCFG_PROXY ]; then
       sed --in-place=.orig \
           -e "s,^PROXY_ENABLED=.*,PROXY_ENABLED=\"yes\",g" \
           -e "s,^HTTP_PROXY=.*,HTTP_PROXY=\"$proxy_spec\",g" \
           $SYSCFG_PROXY
    fi
else
    if [ -f $SYSCFG_PROXY ]; then
       sed --in-place=.orig \
           -e "s,^PROXY_ENABLED=.*,PROXY_ENABLED=\"no\",g" \
           -e "s,^HTTP_PROXY=.*,HTTP_PROXY=\"\",g" \
           $SYSCFG_PROXY
    fi
fi

