#!/bin/bash
#
# chkconfig:    345 31 69
# description:  Simple MT-Proto proxy
#
### BEGIN INIT INFO
# Provides:          mtproto-proxy mtproxy MTProxy
# Required-Start:    $syslog $network $remote_fs
# Required-Stop:     $syslog $network $remote_fs
# Default-Start:     3 5
# Default-Stop:      0 1 2 4 6
# Short-Description: Simple MT-Proto proxy
# Description:       Simple MT-Proto proxy for the Telegram messenger
### END INIT INFO

MTPROXY_BIN=/usr/sbin/mtproto-proxy
MTPROXY_PID=/var/run/mtproto-proxy.pid

if [ -r /etc/rc.status ]; then
  source /etc/rc.status
  START="/sbin/startproc"
  STATUS="/sbin/checkproc"
  SUCCESS="echo \$rc_done"
  FAILURE="echo \$rc_failed"
else
  source /etc/rc.d/init.d/functions
  START="daemon"
  STATUS="status"
  SUCCESS="success; echo"
  FAILURE="failure; echo"
fi

[ -r /etc/sysconfig/mtproto-proxy ] && source /etc/sysconfig/mtproto-proxy

RETVAL=0

case "$1" in
  start)
    echo -n "Starting mtproto-proxy: "
    ${START} ${MTPROXY_BIN} -d -u nobody -S `cat /etc/MTProxy/client-secret` -H ${LISTEN_PORT:-8443} ${OPTIONS} --aes-pwd ${SECRET_FILE:-/etc/MTProxy/proxy-secret} ${CONF_FILE:-/etc/MTProxy/proxy-multi.conf} > /dev/null 2>&1
    RETVAL=$?
    ;;
  stop)
    echo -n "Stopping mtproto-proxy: "
    killproc -p ${MTPROXY_PID} > /dev/null 2>&1
    RETVAL=$?
    ;;
  restart)
    $0 stop
    $0 start
    unset RETVAL
    ;;
  reload)
    echo -n "Reloading mtproto-proxy: "
    killproc -p ${MTPROXY_PID} -HUP > /dev/null 2>&1
    RETVAL=$?
    ;;
  status)
    echo -n "Status of mtproto-proxy: "
    ${STATUS} ${MTPROXY_BIN} > /dev/null 2>&1
    RETVAL=$?
    ;;
  *)
    echo "Usage: $0 {start|stop|status|restart|reload}"
    exit 1
    ;;
esac
[ -z ${RETVAL} ] && exit
[ ${RETVAL} -eq 0 ] && eval "${SUCCESS}" || eval "${FAILURE}"
exit ${RETVAL}
