#!/bin/bash
###############################################################################
#
# Title: Pre Install Script for Salt Installation
# Authors: Shane Lee
# Date: December 2015
#
# Description: This script stops the salt minion service before attempting to
#              install Salt on macOS
#
# Requirements:
#    - None
#
# Usage:
#     This script is run as a part of the macOS Salt Installation
#
###############################################################################
echo "Preinstall started on:" > /tmp/preinstall.txt
date >> /tmp/preinstall.txt
trap 'quit_on_error $LINENO $BASH_COMMAND' ERR

quit_on_error() {
    echo "$(basename $0) caught error on line : $1 command was: $2" >> /tmp/preinstall.txt
    exit -1
}

OSX_VERSION=$(sw_vers | grep ProductVersion | cut -f 2 -d: | tr -d '[:space:]')
MINOR=$(echo ${OSX_VERSION} | cut -f 2 -d.)

###############################################################################
# Stop the service
###############################################################################
stop_service_maverick() {
    echo "Using old (< 10.10) launchctl interface" >> /tmp/preinstall.txt
    if /bin/launchctl list "com.saltstack.salt.minion" &> /dev/null; then
        echo "Stop service: Started..." >> /tmp/preinstall.txt
        launchctl unload -w /Library/LaunchDaemons/com.saltstack.salt.minion.plist
        echo "Stop service: Successful" >> /tmp/preinstall.txt
    fi
}

stop_service_yosemite_and_later() {
    echo "Using new (>= 10.10) launchctl interface" >> /tmp/preinstall.txt
    if /bin/launchctl list "com.saltstack.salt.minion" &> /dev/null; then
        echo "Stop service: Started..." >> /tmp/preinstall.txt
        launchctl disable system/com.saltstack.salt.minion
        launchctl bootout system /Library/LaunchDaemons/com.saltstack.salt.minion.plist
        echo "Stop service: Successful" >> /tmp/preinstall.txt
    fi
}

case $MINOR in
        9 )
                stop_service_maverick;
                ;;
        * )
                stop_service_yosemite_and_later;
                ;;
esac
echo "Preinstall Completed Successfully" >> /tmp/preinstall.txt

exit 0
