#!/system/bin/sh

MODDIR=${0%/*}
RUNTIME_DIR="/data/local/cloudphone"
LOG_FILE="$RUNTIME_DIR/webui-action.log"

mkdir -p "$RUNTIME_DIR" 2>/dev/null || true

action="${1:-status}"

case "$action" in
    start|restart|stop|status)
        ;;
    *)
        echo "unsupported action: $action" >&2
        exit 1
        ;;
esac

if [ "$action" = "status" ]; then
    exec sh "$MODDIR/action.sh" status
fi

if [ "$action" = "start" ]; then
    if sh "$MODDIR/action.sh" status >/dev/null 2>&1; then
        echo "{\"ok\":true,\"action\":\"start\",\"noop\":true,\"reason\":\"already_running\"}"
        exit 0
    fi
fi

(
    echo "[webui_action] action=$action started at $(date '+%F %T')"
    sh "$MODDIR/action.sh" "$action"
    rc=$?
    echo "[webui_action] action=$action finished rc=$rc at $(date '+%F %T')"
    exit "$rc"
) >>"$LOG_FILE" 2>&1 &

echo "{\"ok\":true,\"action\":\"$action\",\"background\":true,\"log\":\"$LOG_FILE\"}"
