#!/bin/bash

services=(docker snapd)

function restart_services(){
  echo "Reloading Systemd - Configfiles"
  sudo systemctl daemon-reload
  for service in ${services[*]} ; do
    echo "Restarting Service $service"
    sudo systemctl restart $service
  done
}

#remove proxy settings from docker
if [[ "${1}" == "off" ]]; then
  for service in ${services[*]} ; do
    echo "TURNING OFF PROXY FOR ${service^^}"
    sudo rm -v "/etc/systemd/system/${service}.service.d/http-proxy.conf"
  done
  restart_services
  exit 0
fi

#populate proxy_ip and proxy_port variables
path=$(dirname $(readlink -f "${0}"))
. "${path}/get_proxy.sh"


echo -n "Username: "
read username
echo -n "Password: "
read -s password
#encpassword=$(perl -MURI::Escape -e 'print uri_escape($ARGV[0]);' "${password}")
#encpassword=$(echo -n ${password}  | sed -e 's/\@/\\x40/g' -e 's/\!/\\x21/g' -e 's/\$/\\x24/g' -e 's/\*/\\x2a/g' -e 's/\%/\\x25/g' -e 's/\&/\\x26/g' -e 's/\#/\\x30/g')
encpassword=$(echo -n ${password}  | xxd -p | sed -e 's/\(..\)/%%\1/g' )

for service in ${services[*]} ; do
  if ! [[ -d "/etc/systemd/system/${service}.service.d" ]] ; then
    sudo mkdir -p "/etc/systemd/system/${service}.service.d/"
  fi
  echo "[Service]" | sudo tee "/etc/systemd/system/${service}.service.d/http-proxy.conf" >/dev/null
  echo 'Environment="HTTP_PROXY=http://'"${username}"':"'"${encpassword}@${proxy_ip}:${proxy_port}/" | sudo tee -a "/etc/systemd/system/${service}.service.d/http-proxy.conf" >/dev/null
  echo 'Environment="HTTPS_PROXY=http://'"${username}"':"'"${encpassword}@${proxy_ip}:${proxy_port}/" | sudo tee -a "/etc/systemd/system/${service}.service.d/http-proxy.conf" >/dev/null
  if [[ -z "$NO_PROXY" ]] ; then
    echo -n 'Environment="NO_PROXY=localhost,127.0.0.1"' | sudo tee -a "/etc/systemd/system/${service}.service.d/http-proxy.conf" >/dev/null
  else
    echo 'Environment="'$(env | grep NO_PROXY)'"' | sudo tee -a "/etc/systemd/system/${service}.service.d/http-proxy.conf" >/dev/null
  fi
done

restart_services
