#!/bin/bash
# 用法:
#   operate_all.sh start|stop [service1 service2 ...]
#   不指定服务名时，默认对全部服务生效。



set -euo pipefail

# 1. 所有服务脚本列表（保持依赖顺序）
declare -a ALL_SERVICES=(
    /data/lp/auth/sh_auth.sh
    /data/lp/gateway/sh_gateway.sh
    /data/lp/modules/app/sh_applet.sh
    /data/lp/modules/file/sh_file.sh
    /data/lp/modules/mall/sh_mall.sh
    /data/lp/modules/service/sh_service.sh
    /data/lp/modules/system/sh_system.sh
)

# 2. 操作只能是 start 或 stop
ACTION="$1"
[[ "$ACTION" =~ ^(start|stop)$ ]] || {
    echo "Usage: $0 start|stop [service1 service2 ...]" >&2
    exit 1
}

shift || true   # 去掉第一个参数，剩下的都是可选服务名

# 3. 要操作的服务列表
declare -a TARGETS=()
if [[ $# -eq 0 ]]; then
    TARGETS=("${ALL_SERVICES[@]}")
else
    # 把用户给的简写映射到完整路径
    for name in "$@"; do
        found=0
        for svc in "${ALL_SERVICES[@]}"; do
            if [[ "$(basename "$(dirname "$svc")")" == "$name" || "$(basename "$svc")" == "sh_${name}.sh" ]]; then
                TARGETS+=("$svc")
                found=1
                break
            fi
        done
        [[ $found -eq 0 ]] && { echo "Unknown service: $name" >&2; exit 1; }
    done
fi

# 4. 开始执行
for svc in "${TARGETS[@]}"; do
    echo "==> $ACTION $(basename "$(dirname "$svc")") ..."
    if ! sh "$svc" "$ACTION"; then
        echo "!!! $svc $ACTION failed, aborting." >&2
        exit $?
    fi
    echo "OK"
done

echo "All requested services $ACTION successfully."
exit 0
