#!/usr/bin/env bash
# proxy-env — install a corporate forward proxy system-wide.
#
# Run on the target host (copy/scp this script there first):
#   sudo PROXY=http://10.0.0.1:8080 bash proxy-env.sh
#
# Optional: NO_PROXY=...   (default: localhost,127.0.0.1,::1)
#
# Writes proxy env vars (lower- and upper-case forms) to /etc/environment
# so every login shell on the host inherits them, and to a profile.d
# drop-in so non-PAM shells (e.g. service ExecStarts that source profile)
# pick them up too. Idempotent — re-runs replace the previous block.
set -euo pipefail

: "${PROXY:?PROXY env var required, e.g. PROXY=http://10.0.0.1:8080}"
NO_PROXY_DEFAULT="localhost,127.0.0.1,::1"
NO_PROXY="${NO_PROXY:-${NO_PROXY_DEFAULT}}"

if [[ ${EUID} -ne 0 ]]; then
  echo "ERROR: must run as root (use sudo)" >&2
  exit 1
fi

MARK_BEGIN="# >>> hrs proxy-env >>>"
MARK_END="# <<< hrs proxy-env <<<"

# Body shared by both files. Both lower- and upper-case forms — different
# tools honor different conventions (curl/wget read lowercase, many Go
# programs read uppercase first).
read -r -d '' BLOCK <<EOF || true
${MARK_BEGIN}
http_proxy=${PROXY}
https_proxy=${PROXY}
HTTP_PROXY=${PROXY}
HTTPS_PROXY=${PROXY}
no_proxy=${NO_PROXY}
NO_PROXY=${NO_PROXY}
${MARK_END}
EOF

# strip_block <file> — remove a previously-written block, if any.
strip_block() {
  local f="$1"
  [[ -f "$f" ]] || return 0
  # sed -i with markers; bracketed exact-match lines.
  sed -i "/^${MARK_BEGIN}\$/,/^${MARK_END}\$/d" "$f"
}

write_block() {
  local f="$1"
  strip_block "$f"
  printf '%s\n' "${BLOCK}" >> "$f"
}

echo "==> writing /etc/environment"
write_block /etc/environment

# /etc/environment is read by PAM at login but NOT sourced by every
# shell (notably non-login service shells). Drop a profile.d snippet
# with `export` so any shell that sources /etc/profile picks them up.
PROFILE_D=/etc/profile.d/hrs-proxy.sh
echo "==> writing ${PROFILE_D}"
{
  echo "${MARK_BEGIN}"
  echo "export http_proxy=${PROXY}"
  echo "export https_proxy=${PROXY}"
  echo "export HTTP_PROXY=${PROXY}"
  echo "export HTTPS_PROXY=${PROXY}"
  echo "export no_proxy=${NO_PROXY}"
  echo "export NO_PROXY=${NO_PROXY}"
  echo "${MARK_END}"
} > "${PROFILE_D}"
chmod 0644 "${PROFILE_D}"

echo
echo "Done. Open a new shell (or \`source ${PROFILE_D}\`) to pick up the vars."
echo "  http_proxy / https_proxy = ${PROXY}"
echo "  no_proxy                 = ${NO_PROXY}"
