#!/bin/sh
# iSH Plus 终端一键美化脚本（完整版：自动修 DNS + 开机换源 + 隐藏自启钩子 + 强制默认 zsh + GitHub 代理克隆 + 自定义 motd）

GH_PROXY="https://gh-proxy-page-bz0.pages.dev/gh"

# 修复 DNS：iSH 默认 resolv.conf 常为空或被重启清空，导致无法解析域名
fix_dns_now() {
  if grep -q "nameserver" /etc/resolv.conf 2>/dev/null; then
    echo "    DNS 已配置，跳过"
  else
    echo "    写入公共 DNS (223.5.5.5 / 119.29.29.29)"
    cp /etc/resolv.conf /etc/resolv.conf.bak 2>/dev/null
    printf "nameserver 223.5.5.5\nnameserver 119.29.29.29\n" > /etc/resolv.conf
  fi
  echo "    解析测试 github.com: $(getent hosts github.com 2>/dev/null | head -1 || echo '仍不可用')"
}

# 换清华镜像源（幂等，自动识别 edge/stable）
setup_mirror() {
  if grep -q "mirrors\." /etc/apk/repositories 2>/dev/null; then
    echo "    已检测到镜像源，跳过换源"
    return
  fi
  echo "    切换为清华镜像"
  cp /etc/apk/repositories /etc/apk/repositories.bak 2>/dev/null
  VER=$(cat /etc/alpine-release 2>/dev/null | cut -d. -f1,2)
  if [ "$VER" = "edge" ] || [ -z "$VER" ]; then
    BASE="https://mirrors.tuna.tsinghua.edu.cn/alpine/edge"
  else
    BASE="https://mirrors.tuna.tsinghua.edu.cn/alpine/v${VER}"
  fi
  printf "%s/main\n%s/community\n" "$BASE" "$BASE" > /etc/apk/repositories
}

# 自定义登录欢迎语（用 figlet 符号艺术字渲染 iSH Plus，带边框兜底）
setup_motd() {
  cat > /etc/motd << 'MOTD'
╔══════════════════════════════════════════════╗
 _ ____  _   _   ____  _           
(_) ___|| | | | |  _ \| |_   _ ___ 
| \___ \| |_| | | |_) | | | | / __|
| |___) |  _  | |  __/| | |_| \__ \
|_|____/|_| |_| |_|   |_|\__,_|___/
╚══════════════════════════════════════════════╝
  🚀 已就绪：清华镜像源 + 自动修DNS + zsh美化 + 语法高亮
  💡 安装软件：apk add <package>
MOTD
  echo "    已写入 /etc/motd（iSH Plus 艺术字，写死不依赖 figlet）"
}

# 生成【隐藏】开机自启钩子（文件名点开头，ls 默认不可见；开机静默执行）
setup_boot_hook() {
  cat > ~/.ish_boot.sh << 'HOOK'
#!/bin/sh
# iSH 开机自愈钩子（隐藏文件，开机静默执行）
# 1. 修 DNS：iSH 重启会清空 /etc/resolv.conf
if ! grep -q "nameserver" /etc/resolv.conf 2>/dev/null; then
  printf "nameserver 223.5.5.5\nnameserver 119.29.29.29\n" > /etc/resolv.conf
fi
# 2. 换清华镜像源（幂等，无则写，自动识别 edge）；换完源后台静默更新索引
if ! grep -q "mirrors\." /etc/apk/repositories 2>/dev/null; then
  VER=$(cat /etc/alpine-release 2>/dev/null | cut -d. -f1,2)
  if [ "$VER" = "edge" ] || [ -z "$VER" ]; then
    BASE="https://mirrors.tuna.tsinghua.edu.cn/alpine/edge"
  else
    BASE="https://mirrors.tuna.tsinghua.edu.cn/alpine/v${VER}"
  fi
  printf "%s/main\n%s/community\n" "$BASE" "$BASE" > /etc/apk/repositories
  ( ( sleep 30; rm -f /lib/apk/db/lock /var/lib/apk/lock 2>/dev/null; apk update >/dev/null 2>&1 </dev/null ) & )   # 延迟30s错峰+清锁，避免与手动apk抢锁
fi
HOOK
  chmod +x ~/.ish_boot.sh
  # 注入 ~/.profile：开机静默调钩子 + 强制进 zsh（iSH 不读 /etc/passwd 的 shell 字段）
  grep -q "ish_boot.sh" ~/.profile 2>/dev/null || cat >> ~/.profile << 'PROF'

# iSH 开机自愈（隐藏钩子，静默执行：修 DNS + 换清华源）
[ -f ~/.ish_boot.sh ] && . ~/.ish_boot.sh >/dev/null 2>&1
# 强制默认进入 zsh
[ -x /bin/zsh ] && exec /bin/zsh
PROF
  echo "    已写入隐藏钩子 ~/.ish_boot.sh 并注入 ~/.profile（开机静默）"
}

echo "==> [0/8] 修复 DNS（本会话）"
fix_dns_now

echo "==> [1/8] 设置隐藏开机自启钩子（修 DNS + 换源 + 默认 zsh）"
setup_boot_hook

echo "==> [2/8] 检测并配置镜像源"
setup_mirror

echo "==> [3/8] 更新索引（先清残留锁，规避 iSH flock bug）"
rm -f /lib/apk/db/lock /var/lib/apk/lock 2>/dev/null
apk update || true

echo "==> [4/8] 逐个安装基础工具（已装则跳过）"
for p in zsh git vim htop tree wget openssh python3 neofetch curl figlet; do
  if apk info -e "$p" >/dev/null 2>&1; then
    echo "    ⊙ $p 已安装，跳过"
  elif apk add "$p" >/dev/null 2>&1; then
    echo "    ✓ $p 已安装"
  else
    echo "    ✗ $p 未安装"
  fi
done

echo "==> [5/8] 安装 zsh 插件（代理优先，失败回退，再失败跳过）"
mkdir -p ~/.zsh
gh_clone() {
  local repo="$1" dest="$2"
  if git clone --depth 1 "${GH_PROXY}/${repo}.git" "$dest" 2>/tmp/ce; then
    echo "    ✓ 代理克隆成功 $repo"; return 0
  fi
  echo "    代理失败: $(tail -1 /tmp/ce)"
  if git clone --depth 1 "https://github.com/${repo}.git" "$dest" 2>/tmp/ce; then
    echo "    ✓ 直连克隆成功 $repo"; return 0
  fi
  echo "    ✗ 直连失败: $(tail -1 /tmp/ce)"; return 1
}
[ -d ~/.zsh/zsh-syntax-highlighting ] || gh_clone zsh-users/zsh-syntax-highlighting ~/.zsh/zsh-syntax-highlighting
[ -d ~/.zsh/zsh-autosuggestions ] || gh_clone zsh-users/zsh-autosuggestions ~/.zsh/zsh-autosuggestions

echo "==> [6/8] 写入 zsh 美化配置"
[ -f ~/.zshrc ] && cp ~/.zshrc ~/.zshrc.bak
cat > ~/.zshrc << 'ZRC'
# 开机自愈：DNS + 换清华源（每次 zsh 启动必跑，比 ~/.profile 更稳）
[ -f /etc/resolv.conf ] && grep -q nameserver /etc/resolv.conf || printf "nameserver 223.5.5.5\nnameserver 119.29.29.29\n" > /etc/resolv.conf
[ -f /etc/motd ] && cat /etc/motd
if ! grep -q "mirrors\." /etc/apk/repositories 2>/dev/null; then
  VER=$(cat /etc/alpine-release 2>/dev/null | cut -d. -f1,2)
  if [ "$VER" = "edge" ] || [ -z "$VER" ]; then
    BASE="https://mirrors.tuna.tsinghua.edu.cn/alpine/edge"
  else
    BASE="https://mirrors.tuna.tsinghua.edu.cn/alpine/v${VER}"
  fi
  printf "%s/main\n%s/community\n" "$BASE" "$BASE" > /etc/apk/repositories
  ( ( sleep 30; rm -f /lib/apk/db/lock /var/lib/apk/lock 2>/dev/null; apk update >/dev/null 2>&1 </dev/null ) & )   # 延迟30s错峰+清锁
fi

autoload -Uz colors && colors
setopt prompt_subst
setopt correct
ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=cyan'
git_branch() {
  local b
  b=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
  [ -n "$b" ] && echo " %F{yellow}($b)%f"
}
PROMPT='%F{red}%n%f%F{208}@ish plus%f:%F{blue}%~%f$(git_branch)
%F{cyan}➜%f '
alias ls='ls --color=auto'
alias ll='ls -la --color=auto'
alias grep='grep --color=auto'
[ -f ~/.zsh/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh ] && source ~/.zsh/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
[ -f ~/.zsh/zsh-autosuggestions/zsh-autosuggestions.zsh ] && source ~/.zsh/zsh-autosuggestions/zsh-autosuggestions.zsh
ZRC

echo "==> [7/8] 自定义登录欢迎语 motd"
setup_motd

echo "==> [8/8] 补充：手动安装插件包（当 clone 不通时）"
echo "    若上面插件克隆失败，在 iSH 执行："
echo "    wget -O zshplugins.tar.gz \"https://qqai.gtimg.com/sandbox/cache/20261001/d77c9812d03e00f164ead8f57f1e6da3/cf40bf6a/zshplugins.tar.gz\""
echo "    mkdir -p ~/.zsh && tar xzf zshplugins.tar.gz -C ~/.zsh"

echo "✅ 完成！后台划掉 iSH 彻底重开即可：自动修 DNS + 自动换源 + 自动进 zsh + 高亮/补全 + iSH Plus 欢迎语"
echo "   验证: cat /etc/motd   cat /etc/resolv.conf   cat /etc/apk/repositories   echo \$0"
