#!/bin/bash

/etc/init.d/nginx stop
exit

CONFIG="/opt/pos/etc/config.ini"
HAS_MOBILE_DEVICES=`cat $CONFIG | grep MOBILE_DEVICES | grep -v grep | grep 1`

if [ ! -e "/usr/sbin/nginx" ]; then
  apt-get -f install nginx
  apt-get clean
fi

if [ "$HAS_MOBILE_DEVICES" != "" ]; then
  echo "upstream pos_cluster {" > /etc/nginx/sites-available/default
  echo "  server 127.0.0.1:3000;" >> /etc/nginx/sites-available/default
  echo "}" >> /etc/nginx/sites-available/default
  echo "" >> /etc/nginx/sites-available/default
  echo "server {" >> /etc/nginx/sites-available/default
  echo "  listen   8080 default;" >> /etc/nginx/sites-available/default
  echo "  server_name  localhost;" >> /etc/nginx/sites-available/default
  echo "  keepalive_timeout 0;" >> /etc/nginx/sites-available/default
  echo "  gzip            on;" >> /etc/nginx/sites-available/default
  echo "  gzip_min_length 1100;" >> /etc/nginx/sites-available/default
  echo "  gzip_comp_level 6;" >> /etc/nginx/sites-available/default
  echo "  gzip_buffers    16 8k;" >> /etc/nginx/sites-available/default
  echo "  gzip_vary       off;" >> /etc/nginx/sites-available/default
  echo "  gzip_proxied    any;" >> /etc/nginx/sites-available/default
  echo "  gzip_types      text/plain text/css application/xml application/javascript application/x-javascript text/json;" >> /etc/nginx/sites-available/default
  echo "  gzip_disable    \"MSIE [1-6].(?!.*SV1)\";" >> /etc/nginx/sites-available/default
  echo "" >> /etc/nginx/sites-available/default
  echo "  location / {" >> /etc/nginx/sites-available/default
  echo "    proxy_pass http://pos_cluster;" >> /etc/nginx/sites-available/default
  echo "  }" >> /etc/nginx/sites-available/default
  echo "" >> /etc/nginx/sites-available/default
  echo "  access_log  /dev/null;" >> /etc/nginx/sites-available/default
  echo "}" >> /etc/nginx/sites-available/default

  if [ ! -e "/usr/bin/starman" ]; then
    /etc/init.d/nginx restart

    # restart mobile if it's running
    MOBILE_PID=`ps -eo pid,args | grep perl | grep mobile  | grep -v grep | cut -c1-6`

    if [ "$MOBILE_PID" != "" ]; then
      kill -9 $MOBILE_PID 2> /dev/null
    fi

    /opt/pos/common/addons/mobile/bin/app.pl --daemon
  else
    /etc/init.d/nginx restart

    # kill old daemon, if running
    ps xa | grep "app\.pl --daemon" | awk '{ print $1 }' | xargs kill -9 2> /dev/null

    for pid in `ps xa | grep plackup | grep -v grep | awk '{ print $1 }'`; do
      kill -9 $pid 2> /dev/null
    done

    for pid in `ps xa | grep starman | grep -v grep | awk '{ print $1 }'`; do
      kill -9 $pid 2> /dev/null
    done

    /opt/pos/common/addons/mobile/bin/run &
  fi
else
  /etc/init.d/nginx stop
fi

