#!/usr/bin/env bash
# デスクトップと Dock を、WIRES-X の導入状況に合わせる(ログイン時と、wx-install-wiresx の最後に実行)
#   wx-desktop          … 導入前なら案内アイコン(①②)を置いて Dock を常に表示
#                         導入後なら WIRES-X の起動アイコンを置き、Dock にも追加して自動で隠す
#   wx-desktop guide    … 導入前の状態にする
#   wx-desktop installed… 導入後の状態にする
set -uo pipefail
export WINEPREFIX="${WINEPREFIX:-$HOME/.wine-wiresx}"
LAB="$HOME/wiresx-lab"
DESK=$(xdg-user-dir DESKTOP 2>/dev/null || true)
[ -n "$DESK" ] && [ "$DESK" != "$HOME" ] || DESK="$HOME/Desktop"
mkdir -p "$DESK"
ICON_FILE="$HOME/.local/share/wiresx-lab/wiresx.png"
DL_URL="https://www.yaesu.com/jp/wires-x/download/"

# SSH から実行したときも、ログイン中のデスクトップの設定を変えられるようにする
UID_=$(id -u)
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ] && [ -S "/run/user/$UID_/bus" ]; then
  export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$UID_/bus"
fi
if [ -z "${DISPLAY:-}" ] && [ -S /tmp/.X11-unix/X0 ]; then export DISPLAY=:0; fi

installed() {
  local p; p=$(cat "$LAB/wiresx.path" 2>/dev/null || true)
  [ -n "$p" ] && [ -f "$p" ] && return 0
  [ -n "$(find "$WINEPREFIX/drive_c" -type f -iname 'wires-x.exe' -not -ipath '*/appdata/*' \
          -not -ipath '*/windows/installer/*' 2>/dev/null | head -1)" ]
}

icon() { [ -f "$ICON_FILE" ] && echo "$ICON_FILE" || echo wiresx-lab; }
browser() {
  local b
  for b in firefox-esr firefox chromium chromium-browser; do command -v "$b" >/dev/null && { echo "$b"; return; }; done
  echo xdg-open
}

# デスクトップのアイコンを「信頼済み」にする(Xfce 4.18 以降は、これがないと実行前に確認が出る)
put() {   # $1=ファイル名 $2=中身
  local f="$DESK/$1"
  printf '%s\n' "$2" >"$f"
  chmod 755 "$f"
  if command -v gio >/dev/null; then
    gio set -t string "$f" metadata::xfce-exe-checksum "$(sha256sum "$f" | cut -d' ' -f1)" 2>/dev/null || true
    gio set -t string "$f" metadata::trusted true 2>/dev/null || true
  fi
}

remove_wine_lnk() {
  # インストーラーが作る Windows 用のショートカット(Pi では開けない)
  find "$DESK" -maxdepth 1 -iname '*.lnk' -delete 2>/dev/null || true
}

guide_icons() {
  put "wiresx-1-download.desktop" "[Desktop Entry]
Type=Application
Name=① WIRES-X をダウンロード
Comment=ブラウザで Yaesu の WIRES-X ダウンロードページを開きます
Exec=$(browser) $DL_URL
Icon=web-browser
Terminal=false"
  put "wiresx-2-install.desktop" "[Desktop Entry]
Type=Application
Name=② WIRES-X を導入
Comment=ダウンロードした WIRES-X を Wine に導入します(wx-install-wiresx)
Exec=xfce4-terminal --title \"WIRES-X の導入\" --geometry 100x30 -x bash -c \"/usr/local/bin/wx-install-wiresx; echo; read -rp 'Enter でこの画面を閉じます' _\"
Icon=system-software-install
Terminal=false"
  rm -f "$DESK/wiresx.desktop"
}

launcher_icon() {
  rm -f "$DESK/wiresx-1-download.desktop" "$DESK/wiresx-2-install.desktop"
  put "wiresx.desktop" "[Desktop Entry]
Type=Application
Name=WIRES-X
Comment=WIRES-X を起動(ログは ~/wiresx-lab/logs)
Exec=/usr/local/bin/wiresx
Icon=$(icon)
Terminal=false"
}

# ---- Dock(xfce4-panel の panel-2)
xq() { xfconf-query -c xfce4-panel "$@" 2>/dev/null; }
panel_ok() { command -v xfconf-query >/dev/null && xq -p /panels/panel-2/plugin-ids >/dev/null; }

CHANGED=0
dock_autohide() {   # $1 = 0(常に表示)/ 2(下端に寄せたときだけ表示)
  [ "$(xq -p /panels/panel-2/autohide-behavior)" = "$1" ] && return 0
  xq -p /panels/panel-2/autohide-behavior -n -t uint -s "$1"; CHANGED=1
}

dock_find_launcher() {   # $1 = .desktop の名前 → プラグイン番号
  local f
  for f in "$HOME"/.config/xfce4/panel/launcher-*/"$1"*.desktop; do
    [ -f "$f" ] && { basename "$(dirname "$f")" | sed 's/launcher-//'; return 0; }
  done
  return 1
}

dock_add_wiresx() {
  local n
  if n=$(dock_find_launcher wiresx-lab-wiresx); then
    local f; f=$(ls "$HOME/.config/xfce4/panel/launcher-$n"/wiresx-lab-wiresx*.desktop | head -1)
    grep -qx "Icon=$(icon)" "$f" || { sed -i "s|^Icon=.*|Icon=$(icon)|" "$f"; CHANGED=1; }
    return 0
  fi
  local ids max check new=() i
  mapfile -t ids < <(xq -p /panels/panel-2/plugin-ids | grep -E '^[0-9]+$')
  max=$(xq -l | sed -n 's|^/plugins/plugin-\([0-9]*\)$|\1|p' | sort -n | tail -1)
  n=$(( ${max:-100} + 1 ))
  mkdir -p "$HOME/.config/xfce4/panel/launcher-$n"
  sed "s|^Icon=.*|Icon=$(icon)|" /usr/share/applications/wiresx-lab-wiresx.desktop \
    >"$HOME/.config/xfce4/panel/launcher-$n/wiresx-lab-wiresx.desktop"
  xq -p "/plugins/plugin-$n" -n -t string -s launcher
  xq -p "/plugins/plugin-$n/items" -n --force-array -t string -s wiresx-lab-wiresx.desktop
  # 判定ツールの手前に入れる(なければ最初の区切り線の手前)
  check=$(dock_find_launcher wiresx-lab-check || true)
  local placed=0 args=()
  for i in "${ids[@]}"; do
    if [ $placed = 0 ]; then
      if [ -n "$check" ] && [ "$i" = "$check" ]; then new+=("$n"); placed=1
      elif [ -z "$check" ] && [ "$(xq -p "/plugins/plugin-$i")" != launcher ]; then new+=("$n"); placed=1; fi
    fi
    new+=("$i")
  done
  [ $placed = 1 ] || new+=("$n")
  for i in "${new[@]}"; do args+=(-t int -s "$i"); done
  xq -p /panels/panel-2/plugin-ids --force-array "${args[@]}"; CHANGED=1
}

dock_remove_wiresx() {
  local n ids args=() i
  n=$(dock_find_launcher wiresx-lab-wiresx) || return 0
  mapfile -t ids < <(xq -p /panels/panel-2/plugin-ids | grep -E '^[0-9]+$')
  for i in "${ids[@]}"; do [ "$i" = "$n" ] || args+=(-t int -s "$i"); done
  xq -p /panels/panel-2/plugin-ids --force-array "${args[@]}"
  xq -p "/plugins/plugin-$n" -r -R
  rm -rf "$HOME/.config/xfce4/panel/launcher-$n"; CHANGED=1
}

panel_restart() { [ "$CHANGED" = 1 ] || return 0; command -v xfce4-panel >/dev/null && pgrep -u "$(id -u)" -x xfce4-panel >/dev/null && xfce4-panel -r >/dev/null 2>&1 || true; }

do_guide() {
  remove_wine_lnk; guide_icons
  if panel_ok; then dock_remove_wiresx; dock_autohide 0; panel_restart; fi
}
do_installed() {
  remove_wine_lnk; launcher_icon
  if panel_ok; then
    dock_add_wiresx; dock_autohide 2; panel_restart
  else
    echo "[注意] Dock の設定はデスクトップにログインしたときに反映します" >&2
  fi
}

case "${1:-auto}" in
  auto) if installed; then do_installed; else do_guide; fi ;;
  guide) do_guide ;;
  installed) do_installed ;;
  *) sed -n '2,6p' "$0"; exit 1 ;;
esac
exit 0
