#!/usr/bin/env bash
# wiresx-pi-lab 初回起動処理(root、ログイン画面より前に1回だけ)
#   - 最初のユーザー(UID 1000)を dialout などに追加
#   - LightDM の既定セッションを Xfce にし、設定で有効なら自動ログイン
#   - ホームに Xfce の設定がなければ /etc/skel から補う
# Raspberry Pi Imager のカスタマイズ(cloud-init)や初回のユーザー作成ウィザードが終わってから動きます
set -uo pipefail
# shellcheck disable=SC1091
[ -f /etc/wiresx-lab.conf ] && . /etc/wiresx-lab.conf
DONE=/var/lib/wiresx-lab/firstboot.done
LOG=/var/log/wiresx-lab/firstboot.log
mkdir -p /var/lib/wiresx-lab /var/log/wiresx-lab
exec >>"$LOG" 2>&1
echo "== $(date '+%F %T') wx-firstboot"

U=$(getent passwd 1000 | cut -d: -f1)
if [ -z "$U" ]; then
  echo "UID 1000 のユーザーがまだいません。次回起動時にもう一度行います"
  exit 0
fi
H=$(getent passwd "$U" | cut -d: -f6)
echo "ユーザー: $U ($H)"

for g in dialout audio video render input plugdev netdev; do
  getent group "$g" >/dev/null && usermod -aG "$g" "$U"
done

# ホームに設定がなければ /etc/skel から補う(Imager でユーザー名を変えた場合など)
if [ -d "$H" ]; then
  for p in .config/xfce4 .config/gtk-3.0 .gtkrc-2.0 .xsessionrc .xinputrc .config/fcitx5; do
    if [ ! -e "$H/$p" ] && [ -e "/etc/skel/$p" ]; then
      mkdir -p "$(dirname "$H/$p")"; cp -a "/etc/skel/$p" "$H/$p"
    fi
  done
  # フォルダ名は英語(Desktop / Downloads など)。日本語名のフォルダがあれば中身を移す
  /usr/local/bin/wx-userdirs "$H"
  mkdir -p "$H/wiresx-lab" "$H/Desktop"
  [ -e "$H/Desktop/WIRES-X ログ" ] || ln -s "$H/wiresx-lab" "$H/Desktop/WIRES-X ログ"
  chown -R "$U:$U" "$H/.config" "$H/.gtkrc-2.0" "$H/.xsessionrc" "$H/.xinputrc" "$H/wiresx-lab" "$H/Desktop" 2>/dev/null
fi

# LightDM: Xfce を既定にし、必要なら自動ログイン
CONF=/etc/lightdm/lightdm.conf
if [ -f "$CONF" ]; then
  python3 - "$CONF" "$U" "${WX_AUTOLOGIN:-on}" <<'PY'
import re, sys
path, user, auto = sys.argv[1], sys.argv[2], sys.argv[3]
s = open(path).read()
m = re.search(r"^\[Seat:\*\]\s*$", s, re.M)
if not m:
    s += "\n[Seat:*]\n"
    m = re.search(r"^\[Seat:\*\]\s*$", s, re.M)
head, body = s[:m.end()], s[m.end():]
nxt = re.search(r"^\[", body, re.M)
sec, rest = (body[:nxt.start()], body[nxt.start():]) if nxt else (body, "")
want = {"user-session": "xfce", "autologin-session": "xfce", "greeter-session": "lightdm-gtk-greeter"}
if auto == "on":
    want["autologin-user"] = user
for k, v in want.items():
    if re.search(rf"^#?\s*{k}=", sec, re.M):
        sec = re.sub(rf"^#?\s*{k}=.*$", f"{k}={v}", sec, count=1, flags=re.M)
    else:
        sec = f"\n{k}={v}" + sec
open(path, "w").write(head + sec + rest)
PY
  echo "LightDM: user-session=xfce autologin=${WX_AUTOLOGIN:-on}"
fi

echo "ページサイズ: $(getconf PAGESIZE) / 機種: $(tr -d '\0' </proc/device-tree/model 2>/dev/null)"
touch "$DONE"
systemctl disable wx-firstboot.service 2>/dev/null || rm -f /etc/systemd/system/multi-user.target.wants/wx-firstboot.service

# デスクトップ起動に切り替えて、そのままログイン画面(または自動ログイン)へ
if [ "$(systemctl get-default)" != graphical.target ]; then
  systemctl set-default graphical.target
  systemctl enable lightdm.service 2>/dev/null || ln -sfn /lib/systemd/system/lightdm.service /etc/systemd/system/display-manager.service
  systemctl daemon-reload
  [ "${WX_NO_START_DM:-0}" = 1 ] || systemctl start --no-block display-manager.service
  echo "グラフィカル起動に切り替えました"
fi
echo "完了"
