#!/bin/bash
#
# Perform necessary Manage setup steps before package is installed.
#

# If we're upgrading from opscode-manage to chef-manage, stop the old services
# if any are running
if ps ax | grep opscode-manage | grep -v grep 2>&1 > /dev/null; then
  echo "Stopping services from previous opscode-manage installation..."
  # Place a "down" file in each service directory. This will prevent the
  # services from coming back up when stopped.
  for i in /opt/opscode-manage/service/*; do touch $i/down ; done
  # Run force-shutdown, to stop everything but the runsv and svlogd processes
  /opt/opscode-manage/embedded/bin/sv force-shutdown /opt/opscode-manage/service/*
  # Stop the runsvdir service. We'll have to try different things based on
  # the init system

  # upstart
  if [ -f /etc/init/opscode-manage-runsvdir.conf ]; then
    service opscode-manage-runsvdir stop
  fi

  # systemd
  if [ -f /usr/lib/systemd/system/opscode-manage-runsvdir-start.service ]; then
    systemctl stop opscode-manage-runsvdir-start
  fi

  # sysvinit
  if [ -f /etc/inittab ] && grep opscode-manage /etc/inittab 2>&1 > /dev/null; then
    sed -i "/^.*opscode-manage.*$/d" /etc/inittab
    kill -HUP 1
  fi

  # Run exit after the service has stopped
  /opt/opscode-manage/embedded/bin/sv exit /opt/opscode-manage/service/*
fi
