#!/usr/bin/env bash

AM_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." >/dev/null 2>&1 && pwd )"
PIDFILE_BASE_DIR=/etc/otel-collector
PIDFILE_DW_BASE_DIR=/etc/directory-watcher
PIDFILE=${PIDFILE_BASE_DIR}/am-agent.pid
PIDFILE_DW=${PIDFILE_DW_BASE_DIR}/directory-watcher.pid

source ${AM_HOME}/bin/tools/serviceHelper
source ${AM_HOME}/bin/tools/message
source ${AM_HOME}/bin/tools/tool-linux

# Start and enable the service on boot
start() {
    enable
    start-otel
    start-dw
}

# Stop and disable the service on boot
stop() {
    stop-otel
    stop-dw
}

# Restart function - Stops and starts the service
restart() {
    restart-otel
    restart-dw
}

start-otel() {
    sudo systemctl enable am-otel-collector.service > /dev/null 2>&1
    sudo systemctl start am-otel-collector.service > /dev/null 2>&1
}

restart-otel() {
    sudo systemctl enable am-otel-collector.service > /dev/null 2>&1
    sudo systemctl restart am-otel-collector.service > /dev/null 2>&1
}

stop-otel() {
    sudo systemctl stop am-otel-collector.service > /dev/null 2>&1
}

start-dw() {
    sudo systemctl enable am-directory-watcher.service > /dev/null 2>&1
    sudo systemctl start am-directory-watcher.service > /dev/null 2>&1
}

stop-dw() {
    sudo systemctl stop am-directory-watcher.service > /dev/null 2>&1
}

restart-dw() {
    sudo systemctl enable am-directory-watcher.service > /dev/null 2>&1
    sudo systemctl restart am-directory-watcher.service > /dev/null 2>&1
}

enable() {
    sudo systemctl enable am-otel-collector.service > /dev/null 2>&1
    sudo systemctl enable am-directory-watcher.service > /dev/null 2>&1
}

disable() {
    sudo systemctl disable am-otel-collector.service > /dev/null 2>&1
    sudo systemctl disable am-directory-watcher.service > /dev/null 2>&1
}

case "$1" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart)
        restart
    ;;
    start-otel)
        start-otel
    ;;
    stop-otel)
        stop-otel
    ;;
    restart-otel)
        restart-otel
    ;;
    start-dw)
        start-dw
    ;;
    stop-dw)
        stop-dw
    ;;
    restart-dw)
        restart-dw
    ;;
    enable)
        enable
    ;;
    disable)
        disable
    ;;
    status)
        check_both_status
    ;;
    *)
        echo $"Usage: $0 {start|stop|restart}"
        exit 1
esac

exit 0
