#!/usr/bin/env bash
set -euo pipefail

# ywz 产品级安装：
# 1. 创建产品用户与目录
# 2. 安装产品 deploy 脚本
# 3. 安装产品 supervisor 配置

if [ "$(id -u)" -ne 0 ]; then
  echo "请使用 root 执行，例如：sudo bash install.sh"
  exit 1
fi

company_root="/opt/inqai"
runtime_root="${company_root}/runtime"
product_id="ywz"
product_root="${company_root}/products/${product_id}"
supervisor_conf="${runtime_root}/supervisor/supervisord.conf"
program_conf="${runtime_root}/supervisor/conf.d/${product_id}.conf"

if ! id -u "$product_id" >/dev/null 2>&1; then
  useradd --system --home "$product_root" --shell /usr/sbin/nologin "$product_id"
fi

install -d -m 0755 \
  "${product_root}" \
  "${product_root}/downloads" \
  "${product_root}/logs" \
  "${product_root}/releases"

chown -R "${product_id}:${product_id}" "$product_root"

cat >"${runtime_root}/bin/deploy_${product_id}.sh" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail

# ywz 发布脚本。
# 用法：
#   deploy_ywz.sh <version> <package_url> <sha256>

if [ "$(id -u)" -ne 0 ]; then
  echo "请使用 root 执行 deploy_ywz.sh"
  exit 1
fi

if [ "$#" -ne 3 ]; then
  echo "用法: deploy_ywz.sh <version> <package_url> <sha256>"
  exit 1
fi

version="$1"
package_url="$2"
expected_sha256="$3"

company_root="/opt/inqai"
runtime_root="${company_root}/runtime"
product_id="ywz"
product_root="${company_root}/products/${product_id}"
release_root="${product_root}/releases"
release_dir="${release_root}/${version}"
download_root="${product_root}/downloads"
download_name="$(basename "${package_url%%\?*}")"
download_file="${download_root}/${download_name}"
temp_file="$(mktemp)"
supervisor_conf="${runtime_root}/supervisor/supervisord.conf"
app_user="${product_id}"
program_name="${product_id}"

cleanup() {
  rm -f "$temp_file"
}

trap cleanup EXIT

install -d -m 0755 "$release_root" "$download_root"

if [ -d "$release_dir" ]; then
  echo "版本已存在: $release_dir"
else
  curl -fL "$package_url" -o "$temp_file"
  actual_sha256="$(sha256sum "$temp_file" | awk '{print $1}')"
  if [ "$actual_sha256" != "$expected_sha256" ]; then
    echo "SHA256 校验失败"
    echo "期望: $expected_sha256"
    echo "实际: $actual_sha256"
    exit 1
  fi

  install -d -m 0755 "$release_dir"

  case "$download_name" in
    *.zip)
      unzip -q "$temp_file" -d "$release_dir"
      ;;
    *.tar.gz|*.tgz)
      tar -xzf "$temp_file" -C "$release_dir"
      ;;
    *)
      echo "不支持的包格式: $download_name"
      exit 1
      ;;
  esac

  if [ ! -f "${release_dir}/start.sh" ]; then
    echo "发布包缺少 start.sh"
    exit 1
  fi

  install -m 0644 "$temp_file" "$download_file"
  chmod 0755 "${release_dir}/start.sh"
  chown -R "${app_user}:${app_user}" "$release_dir"

  if [ -f "${release_dir}/requirements.txt" ]; then
    runuser -u "$app_user" -- python3 -m venv "${release_dir}/.venv"
    runuser -u "$app_user" -- "${release_dir}/.venv/bin/pip" install --upgrade pip
    runuser -u "$app_user" -- "${release_dir}/.venv/bin/pip" install -r "${release_dir}/requirements.txt"
  fi
fi

ln -sfn "$release_dir" "${product_root}/current"

if supervisorctl -c "$supervisor_conf" status "$program_name" 2>/dev/null | grep -q RUNNING; then
  supervisorctl -c "$supervisor_conf" restart "$program_name"
else
  supervisorctl -c "$supervisor_conf" start "$program_name"
fi

for _ in $(seq 1 30); do
  status="$(supervisorctl -c "$supervisor_conf" status "$program_name" 2>/dev/null || true)"
  if printf '%s\n' "$status" | grep -q "RUNNING"; then
    printf '%s\n' "$status"
    break
  fi
  sleep 1
done

if ! supervisorctl -c "$supervisor_conf" status "$program_name" | grep -q "RUNNING"; then
  echo "ywz 未成功进入 RUNNING。"
  tail -n 100 "${product_root}/logs/ywz.stderr.log" || true
  exit 1
fi
EOF

chmod 0755 "${runtime_root}/bin/deploy_${product_id}.sh"

cat >"$program_conf" <<'EOF'
[program:ywz]
command=/bin/bash -lc 'test -x /opt/inqai/products/ywz/current/start.sh || exit 0; cd /opt/inqai/products/ywz/current && exec ./start.sh'
directory=/opt/inqai/products/ywz
user=ywz
autostart=true
autorestart=unexpected
exitcodes=0
priority=20
stdout_logfile=/opt/inqai/products/ywz/logs/ywz.stdout.log
stderr_logfile=/opt/inqai/products/ywz/logs/ywz.stderr.log
EOF

if supervisorctl -c "$supervisor_conf" status >/dev/null 2>&1; then
  supervisorctl -c "$supervisor_conf" reread >/dev/null || true
  supervisorctl -c "$supervisor_conf" update >/dev/null || true
fi

echo "ywz 产品配置已安装。"
echo "下一步："
echo "  sudo ${runtime_root}/bin/deploy_${product_id}.sh <version> <url> <sha256>"
