{{ if eq .chezmoi.os "linux" -}}
#!/bin/bash

{{/* **** unRoot Mode *************************************************** */ -}}
{{/* 如果強制設定unRoot， */}}
{{/* 或是沒有.chezmoi.osRelease.id（因為環境有可能是Synology極精簡環境），直接視同unRoot Mode處理 */}}
{{ if or .unRootMode (not (hasKey .chezmoi.osRelease "id")) -}}
{{/* 部份已由.chezmoiexternal.toml處理了 */ -}}
{{/* 其他自訂手動安裝腳本: */ -}}

{{/* 手動安裝 zsh */ -}}
if ! command -v zsh &> /dev/null; then
  sh -c "$(curl -fsSL https://raw.githubusercontent.com/romkatv/zsh-bin/master/install)" -- -d ~/.local -e no
fi

{{/* 手動安裝 neovim 0.11.1 */ -}}
{{ if eq .chezmoi.arch "amd64"}}
if ! command -v nvim &> /dev/null; then
  curl -LO https://github.com/neovim/neovim/releases/download/v0.11.1/nvim-linux-x86_64.appimage
  chmod u+x nvim-linux-x86_64.appimage
  ./nvim-linux-x86_64.appimage --appimage-extract
  cp -rf squashfs-root/usr/* ~/.local/
  rm -r nvim-linux-x86_64.appimage squashfs-root
fi
{{ end }}

{{/* **** Root Mode ***************************************************** */ -}}
{{ else -}}

{{/* ==== Debian ======================================================== */ -}}
{{ if or (eq .chezmoi.osRelease.id "debian") (eq .chezmoi.osRelease.id "ubuntu") -}}

{{/* ---- 整理待安裝清單 -------------------------------------------------- */ -}}
{{- $aptInstall := .packages.linux.debian.apt -}}
{{- if eq .chezmoi.osRelease.versionCodename "trixie" -}}
{{- $aptInstall = concat .packages.linux.debian.apt .packages.linux.debian.apt_13 -}}
{{ else if and (eq .chezmoi.osRelease.id "debian") (hasKey .chezmoi.osRelease "versionID") (le .chezmoi.osRelease.versionID "12") }}
{{- $aptInstall = concat .packages.linux.debian.apt .packages.linux.debian.apt_12 -}}
{{- end -}}

{{ if eq .chezmoi.osRelease.id "ubuntu" -}}
{{- $aptInstall = .packages.linux.ubuntu.apt -}}
{{ end -}}

apt_packages=( {{ $aptInstall | quoteList | join " " }} )

to_install_apt=()
for package in "${apt_packages[@]}"; do
  to_install_apt+=("$package")
done

echo "  - Installing packages via apt: ${to_install_apt[@]}"
if [ "$EUID" -ne 0 ]; then
  sudo apt install -y "${to_install_apt[@]}"
else
  apt install -y "${to_install_apt[@]}"
fi

{{/* 手動安裝 neovim 0.11.1 */ -}}
{{ if and (eq .chezmoi.osRelease.id "debian") (eq .chezmoi.arch "amd64") (hasKey .chezmoi.osRelease "versionID") (le .chezmoi.osRelease.versionID "12") }}
curl -LO https://github.com/neovim/neovim/releases/download/v0.11.1/nvim-linux-x86_64.appimage
chmod u+x nvim-linux-x86_64.appimage
./nvim-linux-x86_64.appimage --appimage-extract
if [ "$EUID" -ne 0 ]; then
  sudo cp -rf squashfs-root/usr/* /usr/
else
  cp -rf squashfs-root/usr/* /usr/
fi
  rm -r nvim-linux-x86_64.appimage squashfs-root
{{ end }}

{{/* 手動安裝 lazygit */ -}}
{{ if and (eq .chezmoi.osRelease.id "debian") (hasKey .chezmoi.osRelease "versionID") (le .chezmoi.osRelease.versionID "12") }}
LAZYGIT_VERSION=$(curl -s "https://api.github.com/repos/jesseduffield/lazygit/releases/latest" | \grep -Po '"tag_name": *"v\K[^"]*')
curl -Lo lazygit.tar.gz "https://github.com/jesseduffield/lazygit/releases/download/v${LAZYGIT_VERSION}/lazygit_${LAZYGIT_VERSION}_Linux_x86_64.tar.gz"
tar xf lazygit.tar.gz lazygit
if [ "$EUID" -ne 0 ]; then
  sudo install lazygit -D -t /usr/local/bin/
else
  install lazygit -D -t /usr/local/bin/
fi
rm -rf lazygit.tar.gz lazygit
{{ end -}}

{{ end }} {{/* if or (eq .chezmoi.osRelease.id "debian") (eq .chezmoi.osRelease.id "ubuntu") */}}

{{/* ==== Arch Linux / Manjaro ========================================== */ -}}
{{ if or (eq .chezmoi.osRelease.id "manjaro") (eq .chezmoi.osRelease.id "arch") -}}

{{/* ---- 整理待安裝清單 -------------------------------------------------- */ -}}

{{- $pacman_force := .packages.linux.arch.pacman_force -}}
{{- $pacmanInstall := .packages.linux.arch.pacman -}}
{{- $aurInstall := .packages.linux.arch.aur -}}
{{- if .noGUI -}}
{{- $pacmanInstall = concat .packages.linux.arch.pacman .packages.linux.arch.pacman_nogui -}}
{{- else -}}
{{- $pacmanInstall = concat .packages.linux.arch.pacman .packages.linux.arch.pacman_gui -}}
{{- $aurInstall = concat .packages.linux.arch.aur .packages.linux.arch.aur_gui -}}
{{- end -}}

{{ if eq .chezmoi.osRelease.id "manjaro" -}}
{{- $pacman_force = .packages.linux.manjaro.pacman_force -}}
{{- $pacmanInstall = .packages.linux.manjaro.pacman -}}
{{- $aurInstall = .packages.linux.manjaro.aur -}}
{{- if .noGUI -}}
{{- $pacmanInstall = concat .packages.linux.manjaro.pacman .packages.linux.manjaro.pacman_nogui -}}
{{- else -}}
{{- $pacmanInstall = concat .packages.linux.manjaro.pacman .packages.linux.manjaro.pacman_gui -}}
{{- $aurInstall = concat .packages.linux.manjaro.aur .packages.linux.manjaro.aur_gui -}}
{{- end -}}
{{ end -}}

{{/* ---- 安裝腳本 ------------------------------------------------------- */ -}}
{{- /* https://github.com/mriehl/dotfiles/blob/master/run_onchange_packages.sh.tmpl */ -}}
#!/usr/bin/env bash

wait_for_pacman_unlock() {
  local LOCKFILE="/var/lib/pacman/db.lck"
  local MAX_IDLE=10    # 如果沒有 pacman process，最多等這麼久再自動移除殘留
  local WAITED=0

  echo "⏳ 檢查 pacman 鎖定中..."

  while [ -e "$LOCKFILE" ]; do
    if ! pgrep -x pacman >/dev/null && \
       ! pgrep -x packagekitd >/dev/null && \
       ! pgrep -x packagekit >/dev/null; then

       echo "🔍 找不到 pacman 或 PackageKit，疑似殘留鎖檔。"

       if [ "$WAITED" -ge "$MAX_IDLE" ]; then
         echo "🧹 自動移除殘留鎖檔（已閒置 $MAX_IDLE 秒）"
         sudo rm -f "$LOCKFILE"
         break
       fi

       WAITED=$((WAITED + 1))
    fi

    sleep 1
  done

  echo "✅ 鎖定解除，繼續執行。"
}

pacmanForce_packages=( {{ $pacman_force | quoteList | join " " }})
pacman_packages=( {{ $pacmanInstall | quoteList | join " " }} )
aur_packages=( {{ $aurInstall | quoteList | join " " }})

installed_packages=($(pacman -Qq))

is_installed() {
  [[ " ${installed_packages[*]} " =~ " $1 " ]]
}

to_install_pacmanForce=()
for package in "${pacmanForce_packages[@]}"; do
  to_install_pacmanForce+=("$package")
done

# 等待鎖定檔案被移除
wait_for_pacman_unlock

if [[ ${#to_install_pacmanForce[@]} -gt 0 ]]; then
  echo "  - Installing missing packages via pacman: ${to_install_pacmanForce[@]}"
  sudo pacman -Sy --needed --noconfirm --overwrite \* "${to_install_pacmanForce[@]}"
else
  sudo pacman -Sy
fi

# 等待鎖定檔案被移除
wait_for_pacman_unlock

to_install_pacman=()
for package in "${pacman_packages[@]}"; do
  if ! is_installed "$package"; then
    to_install_pacman+=("$package")
  fi
done

if [[ ${#to_install_pacman[@]} -gt 0 ]]; then
  echo "  - Installing missing packages via pacman: ${to_install_pacman[@]}"
  sudo pacman -S --needed --noconfirm --overwrite \* "${to_install_pacman[@]}"
fi

# 等待鎖定檔案被移除
wait_for_pacman_unlock

{{ if eq .chezmoi.osRelease.id "manjaro" -}}
if ! is_installed "yay"; then
  echo "  - Installing yay"
  sudo pacman -S --needed --noconfirm yay
fi
{{ else -}}
if ! command -v yay &> /dev/null; then
    if [ "$EUID" -ne 0 ]; then
      git clone https://aur.archlinux.org/yay-bin.git && cd yay-bin && makepkg -si
    else
      mkdir -p /tmp/yay-build
      useradd -m -G wheel builder && passwd -d builder
      chown -R builder:builder /tmp/yay-build
      echo 'builder ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers
      su - builder -c "git clone https://aur.archlinux.org/yay-bin.git /tmp/yay-build/yay"
      su - builder -c "cd /tmp/yay-build/yay && makepkg -si --noconfirm"
      rm -rf /tmp/yay-build
    fi
fi
{{ end -}}

to_install_aur=()
for package in "${aur_packages[@]}"; do
  if ! is_installed "$package"; then
    to_install_aur+=("$package")
  fi
done

if [[ ${#to_install_aur[@]} -gt 0 ]]; then
  echo "  - Installing missing AUR packages via yay: ${to_install_aur[@]}"
  yay -S --noconfirm "${to_install_aur[@]}"
fi
{{ end -}} {{/* if or (eq .chezmoi.osRelease.id "manjaro") (eq .chezmoi.osRelease.id "arch") */}}

{{ end -}} {{/* else .unRootMode */}}

{{ end -}} {{/* if eq .chezmoi.os "linux" */}}
