#!/usr/bin/sh
set -u

STATE_DIR="/run/almi-lte-recover"
MM_WAS_ACTIVE="${STATE_DIR}/modemmanager-was-active"
RUN_TIMEOUT_SEC="${RUN_TIMEOUT_SEC:-20}"

run_limited() {
    if command -v timeout >/dev/null 2>&1; then
        timeout "$RUN_TIMEOUT_SEC" "$@"
    else
        "$@"
    fi
}

case "${1:-}" in
    pre)
        mkdir -p "$STATE_DIR"
        if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet ModemManager.service 2>/dev/null; then
            echo active > "$MM_WAS_ACTIVE"
            run_limited systemctl stop ModemManager.service >/dev/null 2>&1 || :
        else
            rm -f "$MM_WAS_ACTIVE"
        fi
        ;;
    post)
        if [ -x /usr/sbin/almi-lte-recover ]; then
            /usr/sbin/almi-lte-recover --auto
            rc=$?
        else
            rc=0
        fi

        if [ -e "$MM_WAS_ACTIVE" ] && [ "$rc" -eq 0 ] && command -v systemctl >/dev/null 2>&1; then
            run_limited systemctl start ModemManager.service >/dev/null 2>&1 || :
        fi
        rm -f "$MM_WAS_ACTIVE"
        ;;
esac

exit 0
