#!/bin/bash

#ls -1 /etc/shadowsocks/
#config_8082.json
#config_8083.json
#ss_process_manager.sh
#
#cat /etc/cron.d/shadowsocks
#* * * * * root /etc/shadowsocks/ss_process_manager.sh >/dev/null 2>&1

SS_CONFIG_DIR="/etc/shadowsocks"
PID_FILE_DIR="/var/run"
LOG_FILE_DIR="/var/log"

for ii in $(ls $SS_CONFIG_DIR | grep .json); do
  if [[ $(ps aux | grep "$SS_CONFIG_DIR/$ii" | grep -v grep | awk '{print $2}') ]]; then
    echo "There is a shadowsocks process running using the '$ii' config file"
  else
    echo "No shadowsocks process running for '$ii', attempting to launch one..."
    SERVER_PORT=$(grep server_port $SS_CONFIG_DIR/$ii | cut -d':' -f2 | tr -d ',')
    /usr/local/bin/ssserver -c $SS_CONFIG_DIR/$ii -d start --pid-file "$PID_FILE_DIR/shadowsocks_$SERVER_PORT.pid" --log-file "$LOG_FILE_DIR/shadowsocks_$SERVER_PORT.log"
  fi
done