#!/bin/bash

echo "🔧 OneDrive 文件同步进度查看系统一键部署"

read -p "📄 请输入 OneDrive 日志文件路径（默认 /root/onedrive.log）: " LOG_PATH
LOG_PATH=${LOG_PATH:-/root/onedrive.log}
read -p "🌐 请输入访问端口（默认 8888）: " PORT
PORT=${PORT:-8888}

# 询问是否启用 SSL
read -p "🔒 是否启用 SSL? (y/N): " ENABLE_SSL
ENABLE_SSL=${ENABLE_SSL:-N}

SSL_CONFIG="None"
if [[ "$ENABLE_SSL" =~ ^[Yy]$ ]]; then
    read -p "📂 请输入 SSL 证书存放路径 (默认 /root/ssl): " SSLDIR
    SSLDIR=${SSLDIR:-/root/ssl}
    mkdir -p "$SSLDIR"

    read -p "请输入证书下载地址 (默认 https://sh.digac.icu/ssl/fullchain.pem): " CERT_URL
    CERT_URL=${CERT_URL:-https://sh.digac.icu/ssl/fullchain.pem}

    read -p "请输入私钥下载地址 (默认 https://sh.digac.icu/ssl/privkey.pem): " KEY_URL
    KEY_URL=${KEY_URL:-https://sh.digac.icu/ssl/privkey.pem}

    wget -O "$SSLDIR/fullchain.pem" "$CERT_URL"
    wget -O "$SSLDIR/privkey.pem" "$KEY_URL"

    SSL_CONFIG="(\"$SSLDIR/fullchain.pem\", \"$SSLDIR/privkey.pem\")"
fi

# 安装依赖
if ! command -v python3 &>/dev/null; then
    echo "⚙️ 安装 python3..."
    apt update -y && apt install -y python3
else
    echo "✅ 已安装 python3"
fi

if ! command -v pip3 &>/dev/null; then
    echo "⚙️ 安装 python3-pip..."
    apt install -y python3-pip
else
    echo "✅ 已安装 pip3"
fi

if ! python3 -c "import flask" &>/dev/null; then
    echo "⚙️ 安装 Flask..."
    pip3 install flask --break-system-packages
else
    echo "✅ 已安装 Flask"
fi

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

cat > "$APP_FILE" <<EOF
from flask import Flask, render_template_string, request, redirect, url_for
import os, math, re, datetime

LOG_FILE = "$LOG_PATH"
PAGE_SIZE = 200
PORT = $PORT

app = Flask(__name__)

TEMPLATE = """<html>
<head><meta charset='UTF-8'><title>📦 OneDrive 文件同步进度</title>
<style>
  body { background:#1e1e1e; color:#ccc; font-family: monospace; padding: 20px; }
  .log-line { border-bottom: 1px solid #333; padding: 5px 0; }
  .timestamp { color: #888; margin-right: 10px; display: inline-block; min-width: 160px; }
  input, button { padding: 4px; margin: 2px; background: #333; color: #fff; border: 1px solid #555; }
  .progress { height: 20px; background: #444; border-radius: 4px; margin: 5px 0; overflow: hidden; width: 300px; }
  .bar { height: 100%; background: #4caf50; text-align: center; line-height: 20px; color: #fff; white-space: nowrap; }
  .file-progress { margin-bottom: 10px; }
  .filename { font-weight: bold; }
  a { color: #6cf; text-decoration: none; }
  a:hover { text-decoration: underline; }
</style>
</head>
<body>
<h1>📦 OneDrive 文件同步进度</h1>

<form method="get" style="display:inline-block;">
  🔍 <input name="q" value="{{query or ''}}" placeholder="搜索文件名或日志内容">
  <button>搜索</button>
  <button type="button" onclick="window.location.reload();">刷新</button>
</form>

<form method="post" action="/delete_all" onsubmit="return confirm('确定删除所有日志？');">
  <button>🧹 清空日志</button>
</form>

<hr>

{% if files_progress %}
  <h2>文件同步进度</h2>
  {% for f in files_progress %}
    <div class="file-progress">
      <div class="filename">{{f.name}}</div>
      <div class="progress">
        <div class="bar" style="width:{{f.percent}}%;">{{f.percent}}%</div>
      </div>
    </div>
  {% endfor %}
  <hr>
{% endif %}

<h2>日志内容 (共 {{total_logs}} 条)</h2>

{% for i,entry in logs %}
  <div class="log-line">
    <span class="timestamp">#{{entry.line_no}}</span>
    <span class="timestamp">{{entry.timestamp}}</span>{{entry.text}}
    <form method="post" action="/delete/{{real_index[i]}}" style="display:inline;">
      <button>删除</button>
    </form>
  </div>
{% endfor %}

<div>
  页码:
  {% for p in range(1,total_pages+1) %}
    {% if p == page %}
      <strong>{{p}}</strong>
    {% else %}
      <a href="?page={{p}}{% if query %}&q={{query}}{% endif %}">{{p}}</a>
    {% endif %}
  {% endfor %}
</div>

<!-- Matomo -->
<script>
  var _paq = window._paq = window._paq || [];
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
    var u="//count.fuckj.de/";
    _paq.push(['setTrackerUrl', u+'matomo.php']);
    _paq.push(['setSiteId', '1']);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
  })();
</script>
<!-- End Matomo Code -->

</body>
</html>"""

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

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})\\]',
        r'([A-Z][a-z]{2}) +(\\d{1,2}) (\\d{2}):(\\d{2}):(\\d{2})'
    ]
    for pat in patterns:
        m = re.search(pat, line)
        if m:
            try:
                if len(m.groups()) == 6:
                    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')
                elif len(m.groups()) == 5:
                    month_map = {'Jan':1,'Feb':2,'Mar':3,'Apr':4,'May':5,'Jun':6,
                                 'Jul':7,'Aug':8,'Sep':9,'Oct':10,'Nov':11,'Dec':12}
                    month = month_map.get(m.group(1), 1)
                    now = datetime.datetime.now()
                    dt = datetime.datetime(now.year, month, int(m.group(2)),
                                           int(m.group(3)), int(m.group(4)), int(m.group(5)))
                    return dt.strftime('%Y/%m/%d %H:%M:%S')
            except:
                continue
    return "无时间戳"

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

def parse_file_progress(logs):
    prog_pattern = re.compile(r'(?:Uploading|Progress|uploading)\\s+(\\S+)[^\\d]*(\\d{1,3})%')
    progress_map = {}
    for line in logs:
        m = prog_pattern.search(line)
        if m:
            filename, percent = m.group(1), int(m.group(2))
            progress_map[filename] = max(progress_map.get(filename, 0), percent)
    return [{'name': fn, 'percent': pr} for fn, pr in sorted(progress_map.items())]

@app.route('/')
def index():
    q = request.args.get('q', '').strip()
    page = int(request.args.get('page', 1))

    all_logs = read_logs()
    full_entries = [{'timestamp': extract_timestamp(l), 'text': l.strip(), 'line_no': i+1} for i, l in enumerate(all_logs)]
    filtered_logs = [(i, e) for i, e in enumerate(full_entries) if q.lower() in e['text'].lower()] if q else list(enumerate(full_entries))

    total_logs = len(filtered_logs)
    total_pages = max(1, math.ceil(total_logs / PAGE_SIZE))
    page = max(1, min(page, total_pages))

    logs_page = filtered_logs[(page-1)*PAGE_SIZE : page*PAGE_SIZE]
    real_index = {idx:i for idx,(i,_) in enumerate(logs_page)}

    files_progress = parse_file_progress(all_logs)

    return render_template_string(TEMPLATE,
        logs=logs_page,
        real_index=real_index,
        page=page,
        total_pages=total_pages,
        query=q,
        files_progress=files_progress,
        total_logs=total_logs)

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

@app.route('/delete_all', methods=['POST'])
def delete_all():
    write_logs([])
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=$PORT, ssl_context=$SSL_CONFIG)
EOF

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

[Service]
ExecStart=/usr/bin/python3 $APP_FILE
WorkingDirectory=$INSTALL_DIR
Restart=always
StandardOutput=append:/var/log/onedrive-web.log
StandardError=append:/var/log/onedrive-web.err
User=root

[Install]
WantedBy=multi-user.target
EOF

# 启动服务
systemctl daemon-reexec
systemctl daemon-reload
systemctl enable onedrive-log
systemctl restart onedrive-log

IP=$(hostname -I | awk '{print $1}')
echo -e "\n✅ 部署完成！"
if [[ "$ENABLE_SSL" =~ ^[Yy]$ ]]; then
    echo "🌐 HTTPS 访问地址：https://$IP:$PORT"
    echo "📂 证书目录: $SSLDIR"
else
    echo "🌐 HTTP 访问地址：http://$IP:$PORT"
fi
echo "📂 日志文件：$LOG_PATH"
echo "🛠 管理命令： systemctl restart|stop|status onedrive-log"
