Files
webgui/sbin/set_proxy

117 lines
2.8 KiB
Bash
Executable File

#!/bin/bash
#
# script: set_proxy
#
# Copyright 2005-2024, Lime Technology
#
# call this script (/usr/local/sbin/set_proxy) when /boot/config/proxy.cfg changes
# proxy.cfg is the source of all proxy information
CFG=/boot/config/proxy.cfg
# these files are generated by this script based on the data in proxy.cfg
PROXY_SH=/etc/profile.d/proxy.sh
# random file extension for atomic writes
RND=$RANDOM
VERBOSE=
[[ "$1" == "-v" ]] && VERBOSE=1
# global vars defined later
proxy_active=
proxy_url=
no_proxy=
# write environment variables to /etc/profile.d/proxy.sh
set_proxy_sh() {
local FILE
FILE="${PROXY_SH}"
cat <<EOF >"${FILE}.${RND}"
#!/bin/bash
# Do not edit. This file is autogenerated by /usr/local/sbin/set_proxy
export http_proxy="${proxy_url}"
export https_proxy="${proxy_url}"
export no_proxy="${no_proxy}"
EOF
chmod 755 "${FILE}.${RND}"
mv "${FILE}.${RND}" "${FILE}"
}
# clear environment variables from /etc/profile.d/proxy.sh
unset_proxy_sh() {
local FILE
FILE="${PROXY_SH}"
cat <<EOF >"${FILE}.${RND}"
#!/bin/bash
# Do not edit. This file is autogenerated by /usr/local/sbin/set_proxy
unset http_proxy
unset https_proxy
unset no_proxy
EOF
chmod 755 "${FILE}.${RND}"
mv "${FILE}.${RND}" "${FILE}"
}
# if running, restart_phpfpm when the environment variables change
restart_phpfpm () {
if /etc/rc.d/rc.php-fpm status > /dev/null; then
/etc/rc.d/rc.php-fpm restart > /dev/null
fi
}
# generate proxy files
add_proxy_to_generated_files_and_exit() {
echo "generating proxy files"
set_proxy_sh
. "${PROXY_SH}"
restart_phpfpm
[[ -n "${VERBOSE}" ]] && display_generated_files
exit 0
}
# remove proxy info from all generated files and exit
remove_proxy_from_generated_files_and_exit() {
echo "removing proxy info from generated files"
unset_proxy_sh
. "${PROXY_SH}"
restart_phpfpm
[[ -n "${VERBOSE}" ]] && display_generated_files
exit 0
}
# when verbose mode enabled
display_generated_files() {
echo
display_generated_file "${PROXY_SH}"
}
# when verbose mode enabled
display_generated_file() {
local FILE
FILE=$1
echo "${FILE}"
[[ -f "${FILE}" ]] && cat "${FILE}" || echo "file does not exist"
echo
}
# if no proxy config, remove proxy info from all generated files and exit
[[ ! -f "${CFG}" ]] && remove_proxy_from_generated_files_and_exit
# read current proxy information from /boot/config/proxy.cfg
# shellcheck source=/dev/null
. <(/usr/bin/fromdos <"${CFG}")
# determine proxy information
proxy_url_var="proxy_url_${proxy_active:=}"
proxy_url="${!proxy_url_var}"
# if no active proxies, remove proxy info from all generated files and exit
if [[ "${proxy_active:=0}" == "0" || "${proxy_url}" == "" ]]; then
remove_proxy_from_generated_files_and_exit
fi
# proxies are defined, write generated files
no_proxy="127.0.0.1,localhost"
add_proxy_to_generated_files_and_exit