#!/bin/bash
# ════════════════════════════════════════════════════════════════
# 光湖 · Forgejo UI 自定义部署
# 将光湖风格模板和样式部署到 Forgejo custom 目录
# ════════════════════════════════════════════════════════════════

set -e

REPO_DIR="/data/guanghulab/repo"
CUSTOM_SRC="$REPO_DIR/server/forgejo-custom"

# 查找 Forgejo custom 目录
FORGEJO_CUSTOM=""

# 方法1: 从 app.ini 读取
if [ -f /etc/gitea/app.ini ]; then
  CUSTOM_PATH=$(grep -A2 '\[other\]' /etc/gitea/app.ini 2>/dev/null | grep 'CUSTOM_PATH' | cut -d= -f2 | tr -d ' ')
  if [ -n "$CUSTOM_PATH" ]; then
    FORGEJO_CUSTOM="$CUSTOM_PATH"
  fi
fi

# 方法2: 从 Forgejo 进程参数读取
if [ -z "$FORGEJO_CUSTOM" ]; then
  FORGEJO_CUSTOM=$(cat /proc/$(pgrep -f 'forgejo web' | head -1)/cmdline 2>/dev/null | tr '\0' '\n' | grep -A1 'custom-path' | tail -1)
fi

# 方法3: 默认路径
if [ -z "$FORGEJO_CUSTOM" ]; then
  FORGEJO_CUSTOM="/data/guanghulab/forgejo/custom"
fi

echo "═══════════════════════════════════════"
echo "光湖 · Forgejo UI 部署"
echo "═══════════════════════════════════════"
echo ""
echo "Forgejo Custom 目录: $FORGEJO_CUSTOM"

# 创建目录
mkdir -p "$FORGEJO_CUSTOM/templates/repo"
mkdir -p "$FORGEJO_CUSTOM/public/assets/css"
mkdir -p "$FORGEJO_CUSTOM/public/assets/img"

# 复制模板
echo "▸ 部署自定义模板..."
cp "$CUSTOM_SRC/templates/repo/home.tmpl" "$FORGEJO_CUSTOM/templates/repo/home.tmpl"
echo "✅ 仓库首页模板"

# 复制 CSS
echo "▸ 部署自定义样式..."
cp "$CUSTOM_SRC/public/assets/css/guanghu.css" "$FORGEJO_CUSTOM/public/assets/css/guanghu.css"
echo "✅ 光湖样式"

# 在 head 中注入自定义 CSS（通过 extra_links.tmpl）
echo "▸ 注入自定义CSS到页面头部..."
cat > "$FORGEJO_CUSTOM/templates/head/custom.tmpl" << 'CSSEOF'
<link rel="stylesheet" href="{{AssetUrlPrefix}}/css/guanghu.css?v=1.0">
CSSEOF
echo "✅ CSS注入"

# 重启 Forgejo
echo ""
echo "▸ 重启 Forgejo..."
systemctl restart forgejo
sleep 3

if systemctl is-active --quiet forgejo; then
  echo "✅ Forgejo 已重启"
else
  echo "❌ Forgejo 启动失败，请检查日志"
  exit 1
fi

echo ""
echo "═══════════════════════════════════════"
echo "✅ Forgejo UI 部署完成！"
echo ""
echo "打开 https://guanghulab.com 查看效果"
echo "═══════════════════════════════════════"
