#!/usr/bin/env bash

set -e
# 依赖包列表（已去掉 libgtk-3-0，避免与 24.04 的 libgtk-3-0t64 冲突）
REQUIRED_PACKAGES=(
  "libwebkit2gtk-4.0-37"
  "libayatana-appindicator3-1"
  "openssl"
)

JAMMY_SOURCE_FILE="/etc/apt/sources.list.d/jammy-webkit.list"
JAMMY_PREF_FILE="/etc/apt/preferences.d/webkit-jammy.pref"

UBUNTU_ARCH=""
UBUNTU_VERSION=""

#####################################
# 通用函数
#####################################

log(){ echo -e "[INFO] $*"; }
warn(){ echo -e "[WARN] $*" >&2; }
error_exit(){ echo -e "[ERROR] $*"; exit 1; }

check_root(){
  if [ "$EUID" -ne 0 ]; then
    error_exit "请使用 root 权限运行（例如：sudo $0）"
  fi
}

detect_ubuntu_version(){
  if [ ! -r /etc/os-release ]; then
    error_exit "无法读取 /etc/os-release，无法检测 Ubuntu 版本"
  fi

  # shellcheck source=/dev/null
  . /etc/os-release

  UBUNTU_VERSION="$(echo "$VERSION_ID" | cut -d'.' -f1)"   # 只取主版本号，如 25.10 → 25
  UBUNTU_ARCH="$(dpkg --print-architecture 2>/dev/null || echo unknown)"
  log "检测到系统：Ubuntu ${VERSION_ID} → 主版本号 ${UBUNTU_VERSION} (${UBUNTU_ARCH})"
}

#####################################
# jammy 源 & pin
#####################################

write_jammy_sources(){
  log "写入 jammy 仓库源：${JAMMY_SOURCE_FILE}"

  if [ "${UBUNTU_ARCH}" = "amd64" ]; then
    cat > "${JAMMY_SOURCE_FILE}" << "EOF"
deb http://archive.ubuntu.com/ubuntu jammy main universe
deb http://archive.ubuntu.com/ubuntu jammy-updates main universe
deb http://security.ubuntu.com/ubuntu jammy-security main universe
EOF
  else
    cat > "${JAMMY_SOURCE_FILE}" << "EOF"
deb http://ports.ubuntu.com/ubuntu-ports jammy main universe
deb http://ports.ubuntu.com/ubuntu-ports jammy-updates main universe
deb http://ports.ubuntu.com/ubuntu-ports jammy-security main universe
EOF
  fi
}

write_jammy_pinning() {
  log "写入 apt 优先级策略：仅提升 libwebkit2gtk-4.0-37"

  cat > "${JAMMY_PREF_FILE}" << "EOF"
Package: *
Pin: release n=jammy
Pin-Priority: 100

Package: libwebkit2gtk-4.0-37
Pin: release n=jammy
Pin-Priority: 600
EOF
}

#####################################
# 自动修复 broken 相关
#####################################

fix_existing_broken_if_any(){
  local audit_output
  audit_output="$(dpkg --audit 2>/dev/null || true)"

  if [ -n "${audit_output}" ]; then
    warn "检测到系统存在未完成的安装（broken packages），尝试先自动修复..."
    echo "${audit_output}"
    apt_fix_broken
  else
    log "未发现已有 broken 状态，继续安装流程。"
  fi
}

apt_fix_broken(){
  export DEBIAN_FRONTEND=noninteractive
  log "执行：apt-get -y -f install（自动修复依赖）..."
  if ! apt-get -y -f install; then
    error_exit "自动修复依赖失败，请手动运行 'sudo apt -f install' 检查系统状态。"
  fi
}

apt_install(){
  export DEBIAN_FRONTEND=noninteractive

  log "安装软件包：$*"
  if ! apt-get install -y "$@"; then
    warn "apt-get install 失败，尝试自动修复依赖后重试..."
    apt_fix_broken
    log "依赖已修复，重新尝试安装：$*"
    if ! apt-get install -y "$@"; then
      error_exit "修复依赖后仍无法安装：$*，请手动检查依赖冲突。"
    fi
  fi
}

#####################################
# 安装流程
#####################################

install_with_jammy(){
  write_jammy_sources
  write_jammy_pinning

  apt-get update
  apt_install "${REQUIRED_PACKAGES[@]}"

  log "安装完成，验证 libwebkit2gtk-4.0-37："
  apt-cache policy libwebkit2gtk-4.0-37 || true
}

install_native(){
  log "从本机仓库安装：${REQUIRED_PACKAGES[*]}"
  apt-get update
  apt_install "${REQUIRED_PACKAGES[@]}"
}

#####################################
# 主流程
#####################################

main(){
  check_root
  detect_ubuntu_version
  fix_existing_broken_if_any

  case "${UBUNTU_VERSION}" in
    20|24|25)
      install_with_jammy
      ;;
    22)
      install_native
      ;;
    *)
      error_exit "脚本未适配此 Ubuntu 版本 (${VERSION_ID})"
      ;;
  esac
}

main "$@"
