#!/bin/bash

echo "🔧 OneDrive 多日志查看系统一键部署（自动扫描指定目录下的 *.log 文件）"

echo "🔍 检查是否已安装旧版..."

SERVICE_FILE="/etc/systemd/system/onedrive-log.service"
INSTALL_DIR="/opt/onedrive_log_viewer"

# 清理旧服务
if [[ -f "$SERVICE_FILE" ]]; then
    echo "⚠️ 删除旧 systemd 服务..."
    systemctl stop onedrive-log 2>/dev/null
    systemctl disable onedrive-log 2>/dev/null
    rm -f "$SERVICE_FILE"
fi

# 清理旧目录
if [[ -d "$INSTALL_DIR" ]]; then
    echo "⚠️ 删除旧安装目录..."
    rm -rf "$INSTALL_DIR"
fi

systemctl daemon-reload
echo "✅ 旧版本清理完成"

# --------------------------
#  ① 选择日志目录（默认 /root）
# --------------------------
read -p "📁 请输入日志所在目录（默认 /root）: " LOGDIR
LOGDIR=${LOGDIR:-/root}

echo "📄 将自动扫描目录：$LOGDIR/*.log"

# --------------------------
#  ② 选择访问端口
# --------------------------
read -p "🌐 请输入访问端口（默认 8888）: " PORT
PORT=${PORT:-8888}

apt install -y python3 python3-pip >/dev/null 2>&1
pip3 install flask --break-system-packages >/dev/null 2>&1

mkdir -p "$INSTALL_DIR"
APP_FILE="$INSTALL_DIR/web.py"

echo "📝 正在生成 Python 主程序..."

# 写入变量：PORT & LOGDIR
cat > "$APP_FILE" <<EOF
PORT = $PORT
LOG_DIR = "$LOGDIR"   # ←←← ### 可修改，这里存放日志目录 ###
EOF

# Python 主体
cat >> "$APP_FILE" <<'EOF'
from flask import Flask, render_template_string, request, redirect, url_for
import os, glob, math, re, datetime

PAGE_SIZE = 500
app = Flask(__name__)

def get_log_files():
    return sorted(glob.glob(os.path.join(LOG_DIR, "*.log")))

def read_logs(path):
    if not os.path.exists(path):
        return []
    with open(path, "r", encoding="utf-8", errors="ignore") as f:
        return f.readlines()

def write_logs(path, lines):
    with open(path, "w", encoding="utf-8") as f:
        f.writelines(lines)

def extract_timestamp(line):
    patterns = [
        r"(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})",
        r"\[(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\]",
    ]
    for pat in patterns:
        m = re.search(pat, line)
        if m:
            try:
                dt = datetime.datetime(
                    int(m.group(1)), int(m.group(2)), int(m.group(3)),
                    int(m.group(4)), int(m.group(5)), int(m.group(6))
                )
                return dt.strftime("%Y/%m/%d %H:%M:%S")
            except:
                continue
    return "无时间戳"

def parse_progress(logs):
    pat = re.compile(r"(?:Uploading|Progress|uploading)\s+(\S+)[^\d]*(\d{1,3})%")
    prog = {}
    for line in logs:
        m = pat.search(line)
        if m:
            name, percent = m.group(1), int(m.group(2))
            prog[name] = max(prog.get(name, 0), percent)
    return [{"name": k, "percent": v} for k, v in sorted(prog.items())]

@app.route("/")
def index():
    log_files = get_log_files()
    if not log_files:
        return f"<h2>❌ 无日志文件：{LOG_DIR}/*.log</h2>"

    selected = request.args.get("log", log_files[0])
    if selected not in log_files:
        selected = log_files[0]

    q = request.args.get("q", "").strip()
    page = int(request.args.get("page", 1))

    all_logs = read_logs(selected)
    full = [{"timestamp": extract_timestamp(l), "text": l.strip(), "line_no": i} for i,l in enumerate(all_logs)]

    if q:
        filtered = [(i, e) for i,e in enumerate(full) if q.lower() in e["text"].lower()]
    else:
        filtered = list(enumerate(full))

    total = len(filtered)
    pages = max(1, math.ceil(total / PAGE_SIZE))
    page = max(1, min(page, pages))

    view = filtered[(page-1)*PAGE_SIZE : page*PAGE_SIZE]
    progress = parse_progress(all_logs)

    TEMPLATE = """
    <html>
    <head>
    <meta charset='UTF-8'>
    <title>📦 OneDrive 日志查看器</title>
    <style>
      body { background:#1e1e1e; color:#ddd; font-family: monospace; padding:20px; }
      select,input,button { background:#333; color:#fff; padding:4px; border:1px solid #666; }
      .log-line { border-bottom:1px solid #333; padding:4px 0; }
      .timestamp { color:#888; margin-right:10px; }
      a { color:#6cf; }
      .progress { width:300px; height:20px; background:#444; }
      .bar { height:20px; background:#4caf50; text-align:center; }
    </style>
    </head><body>

    <h1>📦 OneDrive 多日志查看器</h1>

    <form method="get">
      📁 日志：
      <select name="log" onchange="this.form.submit()">
        {% for lf in log_files %}
          <option value="{{lf}}" {% if lf == current_log %}selected{% endif %}>
            {{lf}}
          </option>
        {% endfor %}
      </select>

      🔍 <input name="q" value="{{query or ''}}" placeholder="搜索关键词">
      <button>搜索</button>
      <button type="button" onclick="window.location.reload();">刷新</button>
    </form>

    <form method="post" action="/delete_all?log={{current_log}}" onsubmit="return confirm('确定清空?');">
      <button>🧹 清空日志</button>
    </form>

    <hr>

    <h2>📄 文件同步进度</h2>
    {% for f in progress %}
      <div>{{f.name}}</div>
      <div class="progress"><div class="bar" style="width:{{f.percent}}%">{{f.percent}}%</div></div>
    {% endfor %}
    <hr>

    <h2>📜 日志内容 ({{total_logs}} 条)</h2>
    {% for idx,entry in logs_page %}
      <div class="log-line">
        <span class="timestamp">#{{entry.line_no}}</span>
        <span class="timestamp">{{entry.timestamp}}</span>
        {{entry.text}}
        <form method="post" action="/delete/{{entry.line_no}}?log={{current_log}}" style="display:inline;">
          <button>删除</button>
        </form>
      </div>
    {% endfor %}
    <div style="height: 100px;"></div>
    <p>页码:
    {% for p in range(1,total_pages+1) %}
      {% if p == page %}<b>[{{p}}]</b>
      {% else %}
        <a href="?page={{p}}&log={{current_log}}{% if query %}&q={{query}}{% endif %}">{{p}}</a>
      {% endif %}
    {% endfor %}
    </p>

    <script>
        // 1. 自动滚动到底部的函数
        function scrollToBottom() {
            // 滚动到文档的最底部
            window.scrollTo(0, document.body.scrollHeight);
        }

        // 2. 页面加载完成后立即执行滚动
        // 确保页面刷新后（内容已更新），立即定位到最底部
        window.onload = function() {
            scrollToBottom();
        };

        // 3. 设置 30 秒后自动刷新页面的定时器
        const refreshInterval = 30000; // 10000 毫秒 = 10 秒

        setTimeout(function() {
            // 重新加载页面
            window.location.reload(); 
        }, refreshInterval);
    </script>
    </body></html>
    """

    return render_template_string(TEMPLATE,
        log_files=log_files,
        current_log=selected,
        logs_page=view,
        total_logs=total,
        total_pages=pages,
        page=page,
        query=q,
        progress=progress
    )

@app.route("/delete/<int:line>", methods=["POST"])
def delete_line(line):
    log = request.args.get("log")
    logs = read_logs(log)
    if 0 <= line < len(logs):
        logs.pop(line)
    write_logs(log, logs)
    return redirect(url_for("index", log=log))

@app.route("/delete_all", methods=["POST"])
def delete_all():
    log = request.args.get("log")
    write_logs(log, [])
    return redirect(url_for("index", log=log))

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=PORT)
EOF

# ----------------------------
# 创建systemd服务
# ----------------------------
SERVICE_FILE="/etc/systemd/system/onedrive-log.service"
cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=OneDrive Multi Log Viewer
After=network.target

[Service]
ExecStart=/usr/bin/python3 $APP_FILE
WorkingDirectory=$INSTALL_DIR
Restart=always
User=root

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable onedrive-log
systemctl restart onedrive-log

IP=$(hostname -I | awk '{print $1}')
echo "----------------------------------------------------"
echo "✅ 部署完成！"
echo "🌐 访问地址：http://$IP:$PORT"
echo "📁 日志目录：$LOGDIR"
echo "🛠 systemctl restart onedrive-log"
echo "----------------------------------------------------"
