#!/system/bin/sh

MODDIR=${0%/*}
# shellcheck disable=SC1090
. "$MODDIR/common.sh"

MANAGER_HELPER_JAR="$MODDIR/bin/cloudphone-manager-helper.jar"
MANAGER_HELPER_PORT="${MANAGER_HELPER_PORT:-27655}"

refresh_helper_paths() {
    load_config
    MANAGER_HELPER_PID_FILE="$RUNTIME_DIR/manager-helper.pid"
    MANAGER_HELPER_LOG_FILE="$RUNTIME_DIR/manager-helper.log"
}

is_running() {
    refresh_helper_paths
    [ -f "$MANAGER_HELPER_PID_FILE" ] || return 1
    pid="$(cat "$MANAGER_HELPER_PID_FILE" 2>/dev/null)"
    [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null
}

start_helper() {
    refresh_helper_paths
    ensure_runtime_dir || return 1
    if is_running; then
        log_note "manager helper already running pid=$(cat "$MANAGER_HELPER_PID_FILE" 2>/dev/null)"
        return 0
    fi
    if [ ! -r "$MANAGER_HELPER_JAR" ]; then
        log_note "manager helper jar missing: $MANAGER_HELPER_JAR"
        return 1
    fi
    log_note "starting manager helper port=$MANAGER_HELPER_PORT sock=$SOCK_FILE"
    CLASSPATH="$MANAGER_HELPER_JAR" /system/bin/app_process \
        -Djava.class.path="$MANAGER_HELPER_JAR" \
        /system/bin \
        --nice-name=cloudphone_manager_helper \
        com.cloudphone.managerhelper.Main \
        --sock "$SOCK_FILE" \
        --module-dir "$MODDIR" \
        --port "$MANAGER_HELPER_PORT" \
        >>"$MANAGER_HELPER_LOG_FILE" 2>&1 &
    echo "$!" >"$MANAGER_HELPER_PID_FILE"
    chmod 0644 "$MANAGER_HELPER_PID_FILE" "$MANAGER_HELPER_LOG_FILE" 2>/dev/null || true
}

stop_helper() {
    refresh_helper_paths
    if is_running; then
        pid="$(cat "$MANAGER_HELPER_PID_FILE" 2>/dev/null)"
        log_note "stopping manager helper pid=$pid"
        kill "$pid" 2>/dev/null || true
        sleep 1
        kill -9 "$pid" 2>/dev/null || true
    fi
    rm -f "$MANAGER_HELPER_PID_FILE"
}

case "${1:-start}" in
    start) start_helper ;;
    stop) stop_helper ;;
    restart) stop_helper; start_helper ;;
    status) is_running ;;
    *) echo "usage: manager-helper.sh [start|stop|restart|status]" >&2; exit 1 ;;
esac
