#!/bin/sh
set -u

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

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

sonar_shutdown() {
    if [ "$FAMILYID" == "Bellagio" -o "$FAMILYID" == "Blackjack" ]; then
        if livesonar_is_running; then
            sonar_stop
            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
    fi
}

sonar_start() {
    case "$FAMILYID" in
        Bellagio|Blackjack)
            if ! livesonar_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
            ;;
        *)
            if [ -x /etc/rc.d/rc.stm32 ]; then
                /etc/rc.d/rc.stm32 reset "$@"
            fi
            ;;
    esac
}

sonar_stop() {
    if [ "$FAMILYID" == "Bellagio" -o "$FAMILYID" == "Blackjack" ]; then
        if livesonar_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
        fi
    fi
}

sonar_restart() {
    case "$FAMILYID" in
        Bellagio|Blackjack)
            sonar_stop
            sonar_start "$@"
            ;;
    esac
}

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

    case "$action" in
    shutdown|powerdown)
            sonar_shutdown
        ;;
    start)
            shift
            sonar_start "$@"
        ;;
    stop)
            sonar_stop
        ;;
    restart)
            shift
            sonar_restart "$@"
        ;;
    is-running)
        if [ "$FAMILYID" == "Bellagio" -o "$FAMILYID" == "Blackjack" ]; then
            if livesonar_is_running; then
                return 0 # Running
            else
                return 1 # Shutdown
            fi
        fi
        ;;
    *)
        printf 'Unsupported argument "%s"\n' "$action" >&2
        return 1
        ;;
    esac
}

main "$@"
