#!/usr/bin/env bash
# media-rename —— 宿主机代理，把参数透传进 python 容器执行 SceneRename
#
# 用法:
#   media-rename                            # 处理当前目录
#   media-rename auto                       # 指定 main.py 模式
#   media-rename -p "/hdd/sda1/Quark-Down/苍兰诀 (2022)"
#   media-rename -p 某目录 extract-subs
#   media-rename -h                         # 透传 main.py 帮助
#
# 说明:
#   - 未给 -p/--path 且不是 -h 时，默认取当前目录；
#   - 路径会 realpath 展开，并限制在容器已挂载的范围内；
#   - 有 TTY 时使用 docker exec -it（可交互确认/输入标题年份），无 TTY 时自动降级。
set -euo pipefail

CONTAINER="${MEDIA_RENAME_CONTAINER:-python}"
PYTHON_BIN="/python/media/bin/python"
SCRIPT="/python/media/src/main.py"
ALLOWED_PREFIXES=(/hdd/sda1 /python)

die() { printf '\033[0;31m❌ %s\033[0m\n' "$*" >&2; exit 1; }

args=()
path_found=0
target_path=""
want_help=0
i=1

while (( i <= $# )); do
    arg="${!i}"
    case "$arg" in
        -h|--help)
            want_help=1
            args+=("$arg")
            ;;
        -p|--path)
            args+=("$arg")
            path_found=1
            i=$((i + 1))
            (( i <= $# )) || die "$arg 后面缺少路径参数"
            raw="${!i}"
            target_path="$(realpath -e -- "$raw" 2>/dev/null)" || die "路径不存在或无法解析: $raw"
            args+=("$target_path")
            ;;
        *)
            args+=("$arg")
            ;;
    esac
    i=$((i + 1))
done

if (( ! path_found && ! want_help )); then
    target_path="$(pwd)"
    args+=("-p" "$target_path")
fi

if [[ -n "$target_path" ]]; then
    allowed=0
    for prefix in "${ALLOWED_PREFIXES[@]}"; do
        if [[ "$target_path" == "$prefix" || "$target_path" == "$prefix"/* ]]; then
            allowed=1
            break
        fi
    done
    (( allowed )) || die "路径越界: $target_path 未挂载给容器（仅允许 ${ALLOWED_PREFIXES[*]}）"
fi

exec_opts=(-u 1000:1000)
if [[ -t 0 && -t 1 ]]; then
    exec_opts+=(-it)
fi

exec docker exec "${exec_opts[@]}" "$CONTAINER" "$PYTHON_BIN" "$SCRIPT" "${args[@]}"
