#!/bin/bash

cmsingbox_logfile() {
  printf '%s' "${TRIM_TEMP_LOGFILE:-/tmp/cmsingbox-fnos.log}"
}

cmsingbox_fail() {
  printf '%s\n' "$1" | tee "$(cmsingbox_logfile)" >&2
  return 1
}

network_subnets() {
  docker network inspect -f '{{range .IPAM.Config}}{{println .Subnet}}{{end}}' "$1" 2>/dev/null
}

find_compatible_network() {
  for network_id in $(docker network ls -q); do
    driver="$(docker network inspect -f '{{.Driver}}' "$network_id" 2>/dev/null || true)"
    case "$driver" in macvlan|ipvlan) ;; *) continue ;; esac
    if network_subnets "$network_id" | grep -Fxq "$CMSINGBOX_SUBNET"; then
      docker network inspect -f '{{.Name}}' "$network_id"
      return 0
    fi
  done
  return 1
}

list_overlapping_networks() {
  for network_id in $(docker network ls -q); do
    if network_subnets "$network_id" | grep -Fxq "$CMSINGBOX_SUBNET"; then
      docker network inspect -f '{{.Name}}({{.Driver}})' "$network_id" 2>/dev/null || true
    fi
  done
}

ensure_cmsingbox_network() {
  compatible="$(find_compatible_network || true)"
  if [ -n "$compatible" ]; then
    CMSINGBOX_NETWORK="$compatible"
    return 0
  fi

  CMSINGBOX_NETWORK="cmsingbox-fnos-lan"
  if docker network inspect "$CMSINGBOX_NETWORK" >/dev/null 2>&1; then
    docker network rm "$CMSINGBOX_NETWORK" >/dev/null 2>&1 || \
      cmsingbox_fail "已有同名 Docker 网络 $CMSINGBOX_NETWORK，但无法安全复用或删除。"
  fi

  if ! docker network create \
    --driver macvlan \
    --subnet "$CMSINGBOX_SUBNET" \
    --gateway "$CMSINGBOX_GATEWAY" \
    --opt "parent=$CMSINGBOX_PARENT" \
    --label org.cmsingbox.fnos.managed=true \
    "$CMSINGBOX_NETWORK" >/dev/null; then
    conflicts="$(list_overlapping_networks | paste -sd ', ' -)"
    cmsingbox_fail "无法建立独立网络。与 $CMSINGBOX_SUBNET 冲突的 Docker 网络：${conflicts:-未识别}。若它是 macvlan/ipvlan，新版会自动复用；其他类型网络需先确认无应用使用后再删除或改网段。"
  fi
}

save_selected_network() {
  temporary_env="${TRIM_PKGETC}/network.env.tmp"
  grep -v '^CMSINGBOX_NETWORK=' "${TRIM_PKGETC}/network.env" > "$temporary_env"
  printf 'CMSINGBOX_NETWORK=%s\n' "$CMSINGBOX_NETWORK" >> "$temporary_env"
  mv "$temporary_env" "${TRIM_PKGETC}/network.env"
}

ensure_host_access() {
  host_shim="cmsingbox-shim"
  if ! ip link show dev "$host_shim" >/dev/null 2>&1; then
    ip link add "$host_shim" link "$CMSINGBOX_PARENT" type macvlan mode bridge || \
      cmsingbox_fail "无法创建宿主机访问接口 $host_shim，请确认当前网卡支持 macvlan。"
  fi
  ip link set "$host_shim" up
  ip route replace "$CMSINGBOX_IP/32" dev "$host_shim" || \
    cmsingbox_fail "无法添加宿主机到 CMSingBox 的路由。"
}

deploy_cmsingbox() {
  [ -r "${TRIM_PKGETC}/network.env" ] || cmsingbox_fail "找不到 CMSingBox 网络配置。"
  . "${TRIM_PKGETC}/network.env"
  ensure_cmsingbox_network
  save_selected_network
  ensure_host_access

  mkdir -p "${TRIM_PKGVAR}/data"
  docker pull darkver8/cmsingbox:latest
  docker rm -f cmsingbox-fnos >/dev/null 2>&1 || true
  docker run -d \
    --name cmsingbox-fnos \
    --restart unless-stopped \
    --privileged \
    --env TZ=Asia/Shanghai \
    --network "$CMSINGBOX_NETWORK" \
    --ip "$CMSINGBOX_IP" \
    --volume "${TRIM_PKGVAR}/data:/data" \
    darkver8/cmsingbox:latest >/dev/null
}
