#!/bin/sh
set -u

SCALING_FREQ_DIR=$(find /sys -name "scaling_available_frequencies" -exec dirname {} \;)

sonar_is_running() {
    local pid=$(pidof app_host)
    [ -n "$pid" ]
}

main() {
    local action=${1:-}

    case "$action" in
    shutdown)
        if sonar_is_running; then
            if [ -x /etc/rc.d/rc.sonar ]; then
                /etc/rc.d/rc.sonar stop
            fi

            if [ -x /etc/rc.d/rc.sonar_cpld ]; then
                /etc/rc.d/rc.sonar_cpld stop
            fi

            if [ -f "${SCALING_FREQ_DIR}/cpuinfo_min_freq" ]; then
                cat "${SCALING_FREQ_DIR}/cpuinfo_min_freq" > "${SCALING_FREQ_DIR}/scaling_max_freq"
            fi

            if [ -d "/sys/devices/system/cpu/cpu1" ]; then
                echo 0 > "/sys/devices/system/cpu/cpu1/online"
            fi
        fi
        ;;
    start)
        if ! sonar_is_running; then
            if [ -d "/sys/devices/system/cpu/cpu1" ]; then
                echo 1 > "/sys/devices/system/cpu/cpu1/online"
            fi

            if [ -f "${SCALING_FREQ_DIR}/cpuinfo_max_freq" ]; then
                cat "${SCALING_FREQ_DIR}/cpuinfo_max_freq" > "${SCALING_FREQ_DIR}/scaling_max_freq"
            fi

            if [ -x /etc/rc.d/rc.sonar_cpld ]; then
                /etc/rc.d/rc.sonar_cpld start
            fi

            if [ -x /etc/rc.d/rc.sonar ]; then
                /etc/rc.d/rc.sonar start
            fi
        fi
        ;;
    is-running)
        if sonar_is_running; then
            return 0 # Running
        else
            return 1 # Shutdown
        fi
        ;;
    *)
        printf 'Unsupported argument "%s"\n' "$action" >&2
        return 1
        ;;
    esac
}

main "$@"