#!/bin/sh

# Downloads latest Telegram config file(s) and restarts teleproxy upon success

# Random servers are emitted by Telegram server on every request, so this script
# is set as weekly cron job because it will result in service restart virtually
# upon every run

T_CONF=/usr/share/teleproxy/proxy-multi.conf
T_CONF_DOWNLOAD=/usr/share/teleproxy/proxy-multi.conf-downloaded

# Get it:
curl -s --max-time 60 https://core.telegram.org/getProxyConfig -o $T_CONF_DOWNLOAD

if [ ! -f "$T_CONF_DOWNLOAD" ]; then
  echo "Failed to download Teleproxy configuration file to ${T_CONF_DOWNLOAD}!"
  exit 1
fi

if ! grep -q "proxy_for " $T_CONF_DOWNLOAD &>/dev/null; then
  echo "Downloaded Teleproxy configuration file ${T_CONF_DOWNLOAD} appears invalid!"
  exit 1
fi

if ! diff -q $T_CONF $T_CONF_DOWNLOAD &>/dev/null; then
  # remove symlink so that we copy real file
  rm -f $T_CONF
  /bin/cp $T_CONF_DOWNLOAD $T_CONF
  # if not running, bail
  /sbin/service teleproxy status  >/dev/null 2>&1 || exit 0
  # if running, restart
  /sbin/service teleproxy reload >/dev/null 2>&1 || echo \
      "Data upgrade for Teleproxy failed"
fi
