#!/bin/bash

. /etc/appliance/scriptsLib-3.0/maintenance.lib

disable_svc() {
    local svc=$1
    local marker_dir=/etc/virtualhosting/maintenance/markers
    if chkconfig $1; then
        touch $marker_dir/$svc
        chkconfig $svc off
    fi
}

#start the installation of service
# create the install counter for the service
if [ $1 ]; then
    touch /etc/virtualhosting/maintenance/install/$1
fi

# checks if expected state
maintenance_flag=`isMaintenanceMode`
if [ $maintenance_flag == '1' ]; then
    # nothing to be done here
    exit 0
fi

# declares start of Maintenance Mode
enterMaintenanceMode
if [ $? != 0 ]; then
    log_messages 1 "NORMAL" "Could not enter maintenance mode"
    exit 1
fi

# checks for maintenance_state for previous attempts
state=`getMaintenanceState`
if [ $state != "$STATE_PREP_PRE_MAINTENANCE" ]; then
    # nothing to be done here
    exit 0
fi

# the status() and the stop() functions of the earlier(<3.5) scripts will not work
# because egrep became a shell script that just invokes /bin/grep -E. hence,
# rather than stop webppliance through /etc/rc.d/init.d/webppliance, we will 
# simply implement the webppliance stop() ourselves
# NOTE -- earlier versions of set_pre_maintenance called `safestop', but that involves
# acquiring a domain lock, which in turn requires some other python scripts to have 
# been upgraded -- hence, we stop() webppliance instead of safestop()
all_procs=`ps --columns=512 -e --no-headers -o pid,args`
webppliance_pids=`echo "$all_procs" |grep "python.* /usr/lib/opcenter/ocwstart.pyc" |awk -Wsource='{ printf $1 " "; }'`
if [ ! "$webppliance_pids" = "" ]; then
  kill $webppliance_pids 2>/dev/null 1>/dev/null
  retval=$?
  if [ "$retval" -eq "0" ]; then
    rm -f /var/lock/subsys/webppliance
    log_messages 0 "PREP_PRE_MAINTENANCE" "stopping WEBppliance"
  else
    log_messages 1 "PREP_PRE_MAINTENANCE" "Could not stop WEBppliance, but continuing anyway"
    # the system pid's for future reference
    log_messages 1 "PREP_PRE_MAINTENANCE" "$all_procs"
  fi
fi

# XXX wait for CLI to finish (skip for now)

disable_svc crond
# explicitly shut it down because we really can't have it
# running (in case customers are doing odd things in cron jobs)
/etc/rc.d/init.d/crond stop

# SXC private server hack to fix /dev/hda1 not pointing to correct dev
# (21761)
/usr/local/sbin/zaphda1

/sbin/quotaoff -aug

# set pre_maintenance_state
setMaintenanceState $STATE_PRE_MAINTENANCE
if [ $? != 0 ]; then
    log_messages 1 "PREP_PRE_MAINTENANCE" "Could not enter PRE_MAINTENANCE"
    exit 1
fi
