{{ if eq .chezmoi.os "linux" -}}


{{ if eq .chezmoi.osRelease.id "manjaro" -}}
{{- /* 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=( {{.packages.linux.manjaro.pacman_force | quoteList | join " " }})
pacman_packages=( {{.packages.linux.manjaro.pacman | quoteList | join " " }})
aur_packages=( {{.packages.linux.manjaro.aur | 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 -S --needed --noconfirm "${to_install_pacmanForce[@]}"
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 "${to_install_pacman[@]}"
fi

# 等待鎖定檔案被移除
wait_for_pacman_unlock

if ! is_installed "yay"; then
  echo "  - Installing yay"
  sudo pacman -S --needed --noconfirm yay
fi

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 -}}


{{ end -}}
