#!/bin/bash
NGINX_LOG="/var/log/nginx/access.log"
LAST_POS_FILE="/var/www/audio/stats/.last_pos"
PLAY_LOG="/var/www/audio/stats/play.log"

# 读取上次处理到的位置
if [ -f "$LAST_POS_FILE" ]; then
  LAST_POS=$(cat "$LAST_POS_FILE")
else
  LAST_POS=0
fi

# 只处理新增的日志（从上次位置开始）
tail -n +$((LAST_POS + 1)) "$NGINX_LOG" | python3 - "$PLAY_LOG" <<'PY'
import sys, re, urllib.parse
from datetime import datetime

play_log = sys.argv[1]
new_records = []

for line in sys.stdin:
    m = re.search(r'stats/track\.json\?([^\s"]+)', line)
    if not m: 
        continue
    qs = m.group(1)
    q = urllib.parse.parse_qs(qs, keep_blank_values=True)
    id_  = (q.get('id') or [''])[0]
    name = urllib.parse.unquote((q.get('name') or [''])[0])
    user = urllib.parse.unquote((q.get('user') or [''])[0])

    dm = re.search(r'\[(\d{2}/\w{3}/\d{4}):(\d{2}:\d{2}:\d{2})', line)
    if dm:
        d = datetime.strptime(dm.group(1), '%d/%b/%Y')
        logdate = d.strftime('%Y-%m-%d')
        time = dm.group(2)
    else:
        d = datetime.now()
        logdate = d.strftime('%Y-%m-%d')
        time = d.strftime('%H:%M:%S')

    week  = f'{d:%Y}-W{d:%V}'
    month = d.strftime('%Y-%m')
    year  = d.strftime('%Y')

    if id_ and name:
        new_records.append(f'{logdate} {time}|{logdate}|{week}|{month}|{year}|{id_}|{name}|{user}')

# 追加到 play.log
if new_records:
    with open(play_log, 'a', encoding='utf-8') as f:
        f.write('\n'.join(new_records) + '\n')
PY

# 更新处理位置（当前日志总行数）
wc -l < "$NGINX_LOG" > "$LAST_POS_FILE"

# 生成统计
/var/www/audio/stats/generate_json.sh
