#!/bin/sh

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
#       Copyright (C) 2012-4 Michael D. Taht, Toke Høiland-Jørgensen, Sebastian Moeller

# allow passing in the IFACE as first command line argument

[ -n "$IFACE" ] || exit 1

. /etc/sqm/sqm.conf
. ${SQM_LIB_DIR}/functions.sh
. ${SQM_LIB_DIR}/defaults.sh

check_state_dir
# log file for the most recent sqm instance stop
if [ "$SQM_DEBUG" -eq "1" ] ; then
    SQM_DEBUG_LOG="${SQM_STOP_LOG}"
    OUTPUT_TARGET="${SQM_DEBUG_LOG}"
    echo "stop-sqm: Log for interface ${IFACE}: $(date)"  > "${OUTPUT_TARGET}"
fi

if [ ! -f "${SQM_STATE_DIR}/${IFACE}.state" ] ; then
    sqm_error "State file does not exist; SQM was not running on interface ${IFACE}"
    exit 1
fi
STATE_FILE="${SQM_STATE_DIR}/${IFACE}.state"

if [ -z "${SCRIPT}" ] ; then
    sqm_error "SCRIPT value is not defined in /etc/sqm/${IFACE}.iface.conf"
    sqm_error "Please check your configuration and try again."
    exit 1
fi

sqm_trace; sqm_trace "$(date): Stopping." # Add some space and a date stamp to verbose log output and log files to separate runs
sqm_log "Stopping SQM on ${IFACE}"

# make sure to only delete the ifb associated with the current interface
CUR_IFB=$( get_ifb_associated_with_if ${IFACE} )
[ -z "$CUR_IFB" ] && CUR_IFB=$( ifb_name ${IFACE} )

if [ ! -f "${SQM_LIB_DIR}/$SCRIPT" ]; then
    sqm_error "SQM script ${SCRIPT} not found!"
    exit 1
fi

. "${SQM_LIB_DIR}/$SCRIPT"

sqm_stop
rm -f "${STATE_FILE}"

exit 0
