#!/bin/bash
#
# cohesity-agent        Start/stop Cohesity Linux Agent
#
# chkconfig: 2345 20 40
# description: Starts Cohesity's Linux Agent
#
# Copyright 2016 Cohesity Inc.
#
# Author: Sachin Gaikwad (sachin@cohesity.com)
#
# Description:
# This script provides operations like start, stop, status to manage Cohesity
# Linux Agent process on a Linux machine.
#
### BEGIN INIT INFO
# Provides:       linux_agent_exec
# Required-Start:
# Required-Stop:
# Default-Start:  2 3 4 5
# Default-Stop:   2 3 4 5
# Short-Description: Cohesity Linux Agent service
# Description:    Cohesity Linux Agent service
### END INIT INFO

#set -x

# This variable is set by external script (setup.sh) when installing the agent
# on system. This also act as a small config which saves what/where/for-whom did
# we install Cohesity Agent. This information is used by installer/setup.sh when
# uninstalling the agent.
COHESITY_USER="COHESITY_USER_TEMPLATE"
COHESITY_GROUP="COHESITY_GROUP_TEMPLATE"
COHESITY_INSTALL_DIR="COHESITY_INSTALL_DIR_TEMPLATE"
COHESITY_BIN_DIR="COHESITY_INSTALL_DIR_TEMPLATE/software/crux/bin"
COHESITY_USER_CREATED=COHESITY_USER_CREATED_TEMPLATE

SERVICE_NAME="cohesity-agent"

f_start() {
  $COHESITY_BIN_DIR/linux_agent.sh start "INIT_SYSTEM_TYPE_TEMPLATE"
}

f_stop() {
  $COHESITY_BIN_DIR/linux_agent.sh stop
}

f_status() {
  $COHESITY_BIN_DIR/linux_agent.sh status
}

f_version() {
  $COHESITY_BIN_DIR/linux_agent.sh version
}

# Let's first make sure we are running as 'root' (UID=0).
# or we are running as COHESITY_USER (started via one of the init system)
# else ask user to run as root/sudo.
COHESITY_USER_UID=`id -u COHESITY_USER_TEMPLATE`
if [ $UID -ne 0 -a $UID -ne $COHESITY_USER_UID ]; then
  echo "Please start the script as root or sudo!"
  exit 1
fi

# Create agent service directory in /var/run/ where pid file is created for
# saving parent process's pid. This is usually created by init system's startup
# script. But in case when init system is not-in-use, we create this directory
# here. User must be running this script as 'root' when not using init system.
if [[ $UID == 0 ]]; then
  mkdir -p AGENT_SERVICE_DIR_TEMPLATE
  chmod 755 AGENT_SERVICE_DIR_TEMPLATE
  chown COHESITY_USER_TEMPLATE:COHESITY_GROUP_TEMPLATE AGENT_SERVICE_DIR_TEMPLATE
fi

case "$1" in
  start)
    echo "Starting $SERVICE_NAME"
    f_start
    ;;
  stop)
    echo "Stopping $SERVICE_NAME"
    f_stop
    ;;
  restart)
    echo "Stopping $SERVICE_NAME"
    f_stop
    echo "Starting $SERVICE_NAME"
    f_start
    ;;
  status)
    f_status
    ;;
  version)
    f_version
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|status|version}"
    exit 1
esac
exit 0
