#!/bin/bash

# we under root?
#if [ "$UID" -ne "0" ]
#then
#  echo "You need root privelegies."
#  exit 1
#fi

. /opt/sarch/base/etc/env.conf
. /opt/sarch/base/etc/install.conf

LAUNCHCTL="/bin/launchctl"
LAUNCHD_SKM_PATROL="/Library/LaunchDaemons/com.videonext.skm-patrol.plist"

change_master_ip()
{                                                                                                                   
  [ ! -n "$1" ] && return                                                                                                                                            
  master_ip=$1

  sed -i -e "s/.* s_master//" /etc/hosts 
  echo "$master_ip s_master" >> /etc/hosts 

  su apl -c "sed -i -e 's/.*$master_ip.*//' /var/opt/sarch/pgsql/pg_hba.conf"
  su apl -c "echo \"host    all     all     $master_ip  255.255.255.255 trust\" >>  /var/opt/sarch/pgsql/pg_hba.conf"                                      
  # Remove PHP WSDL cache
  rm -f /tmp/wsdl-* 2>/dev/null
}

autostart() 
{
echo "
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
<plist version=\"1.0\">
<dict>
	<key>Debug</key>
	<false/>
	<key>KeepAlive</key>
	<false/>
	<key>Label</key>
	<string>com.videonext.skm</string>
	<key>ProgramArguments</key>
	<array>
		<string>/opt/sarch/sly/Darwin/bin/daemondo</string>
		<string>--label=com.videonext.skm</string>
		<string>--start-cmd</string>
		<string>/opt/sarch/sly/Darwin/bin/control</string>
		<string>start</string>
		<string>;</string>
		<string>--stop-cmd</string>
		<string>/opt/sarch/sly/Darwin/bin/control</string>
		<string>stop</string>
		<string>;</string>
		<string>--restart-cmd</string>
		<string>/opt/sarch/sly/Darwin/bin/control</string>
		<string>restart</string>
		<string>;</string>
		<string>--pid=none</string>
	</array> " > /Library/LaunchDaemons/com.videonext.skm.plist
if [ "$1" = "off" ]
then
     echo "
	<key>RunAtLoad</key>
	<false/> " >> /Library/LaunchDaemons/com.videonext.skm.plist
else
     echo "
     	<key>RunAtLoad</key>
        <true/> " >> /Library/LaunchDaemons/com.videonext.skm.plist
fi

echo "
</dict>
</plist>" >> /Library/LaunchDaemons/com.videonext.skm.plist
  
}

case "$1" in
  start)
        # sanity checks for apache && php
        if [ ! -L /usr/libexec/apache2/libphp5.so ] ; then
          mv /usr/libexec/apache2/libphp5.so /usr/libexec/apache2/libphp5.so_moved_by_skm
          ln -s /opt/sarch/imp/lib/libphp5.so /usr/libexec/apache2/libphp5.so 
        fi

        # Disable Spotlight
	/opt/sarch/sly/Darwin/bin/spotlight_off > /dev/null         

	# Restart apache   
	#/bin/launchctl unload /System/Library/LaunchDaemons/org.apache.httpd.plist 2>/dev/null
        #/bin/launchctl unload /Library/LaunchDaemons/org.apache-i386.httpd.plist 2>/dev/null
        #/bin/launchctl load -w /Library/LaunchDaemons/org.apache-i386.httpd.plist
        /opt/sarch/sly/Darwin/bin/setup_launch_httpd install
	
	# Attach RAM cache
#	/opt/sarch/cache/bin/cachectl start
	
        [ -f /var/opt/sarch/wd/keep ] || mkdir -p /var/opt/sarch/wd
        echo run > /var/opt/sarch/wd/keep
	su apl -c "/opt/sarch/sly/Darwin/bin/start_server"
        $LAUNCHCTL load -w $LAUNCHD_SKM_PATROL
        ;;
  stop)
        echo stop > /var/opt/sarch/wd/keep 
        $LAUNCHCTL unload -w $LAUNCHD_SKM_PATROL
	su apl -c "/opt/sarch/sly/Darwin/bin/stop_server"
	# Detach RAM cache
#	/opt/sarch/cache/bin/cachectl stop
        ;;

  status)
        echo -n "version: "; cat /opt/sarch/sly/Darwin/etc/VERSION |cut -f1-3 -d.;
    
	[ "`ps aux|grep cam_patrol|grep -v grep`" ] && echo "running: yes" || echo "running: no";

	[ "`cat /Library/LaunchDaemons/com.videonext.skm.plist 2>/dev/null|grep -A 1 RunAtLoad|grep true`" ] && echo "autostart: yes" || echo "autostart: no";     
        if [ `cat /opt/sarch/sly/Darwin/etc/VERSION|grep -i "stratusx"` ]
	then
            is_master="no";
            master_ip=`cat /etc/hosts|grep s_master|cut -f1 -d' '`;

            for ip_addr in `/sbin/ifconfig |grep -oE "inet [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+"|cut -d ' ' -f 2`
            do
                [ "$ip_addr" == "$master_ip" ] && is_master="yes";
            done

            echo "master: $is_master";       
            echo "master_ip: $master_ip";
        else 
            echo "master: yes";   
            echo "master_ip: localhost";
        fi

        if [ -f /opt/sarch/var/sm/status ]
        then
            echo -n "storage: "
            cat /opt/sarch/var/sm/status|tr "[:upper:]" "[:lower:]"
        fi

	echo "netname: "`/opt/sarch/sly/Darwin/bin/netname`

        ;;
  change_master_ip)
	change_master_ip $2
	if [ "`ps aux|grep cam_patrol|grep -v grep`" ]
	then 
           $LAUNCHCTL unload -w $LAUNCHD_SKM_PATROL
	   su apl -c "/opt/sarch/sly/Darwin/bin/stop_server"
	   su apl -c "/opt/sarch/sly/Darwin/bin/start_server"
           $LAUNCHCTL load -w $LAUNCHD_SKM_PATROL
	fi
	;;
  check_layout)        
        echo -n "layout: ";
        su apl -c /opt/sarch/sm/bin/sm_layout 2>/dev/null >&2
        [ $? == 0 ] && echo "ok" || echo "failed"
        ;;
  restart)
    /opt/sarch/sly/Darwin/bin/control stop
    sleep 2   # let sm_engine finish
    /opt/sarch/sly/Darwin/bin/control start
    ;;

  autostart)
	autostart $2
    ;;
  apply_patch)
	if [ ! -n "$2" ] ; then 
	  echo "No patch file provided"; 
	  exit 1;
	fi
	decripted_patch=`echo $2|awk 'BEGIN { FS = ".gpg" } ; { print $1 }'`
	silent_mode=''; [ "$3" == "silent" ] && silent_mode="echo |";
	if [ -f $decripted_patch ] ; then
	  eval "$silent_mode$decripted_patch" 2>&1
	else
	  # decoding firstly
          /opt/sarch/imp/bin/gpg --yes --homedir "/opt/sarch/vpatch/etc/.pg" $2
	  [ $? == 0 ] && (chmod +x $decripted_patch && eval "$silent_mode$decripted_patch" 2>&1); 
	fi 
        rm -f $decripted_patch  >/dev/null 2>&1
   ;;

  uninstall)
        /opt/sarch/sly/Darwin/bin/control stop 1>/dev/null 2>&1
        /opt/sarch/sly/Darwin/bin/setup_launch_httpd deinstall  1>/dev/null 2>&1
        /opt/sarch/base/bin/deinstall.root 2>&1
        rm -rf /opt/sarch 1>/dev/null 2>&1
        # Remove PostgreSQL data completely
        rm -rf /var/opt/sarch/pgsql 1>/dev/null 2>&1
        dscl . -delete /Users/apl 1>/dev/null 2>&1
   ;;

  *)
    echo "Usage: `basename "\$0"` {start|stop|restart|status|autostart [on]|[off]|change_master_ip [ip addr]|apply_patch [patch file]}"
    exit 1
esac
