#!/bin/bash

LOG_FILE="/var/www/audio/stats/play.log"
PERIOD=$1  # day, week, month, year
AUDIO_ID=$2

case $PERIOD in
  "day")
    TODAY=$(date "+%Y-%m-%d")
    if [ -z "$AUDIO_ID" ]; then
      # 所有音频的今日统计
      grep "$TODAY" "$LOG_FILE" | awk -F'|' '{print $6, $7}' | sort | uniq -c | sort -rn
    else
      # 指定音频的今日统计
      grep "$TODAY" "$LOG_FILE" | grep "|$AUDIO_ID|" | wc -l
    fi
    ;;
  "week")
    WEEK=$(date "+%Y-W%V")
    if [ -z "$AUDIO_ID" ]; then
      grep "$WEEK" "$LOG_FILE" | awk -F'|' '{print $6, $7}' | sort | uniq -c | sort -rn
    else
      grep "$WEEK" "$LOG_FILE" | grep "|$AUDIO_ID|" | wc -l
    fi
    ;;
  "month")
    MONTH=$(date "+%Y-%m")
    if [ -z "$AUDIO_ID" ]; then
      grep "$MONTH" "$LOG_FILE" | awk -F'|' '{print $6, $7}' | sort | uniq -c | sort -rn
    else
      grep "$MONTH" "$LOG_FILE" | grep "|$AUDIO_ID|" | wc -l
    fi
    ;;
  "year")
    YEAR=$(date "+%Y")
    if [ -z "$AUDIO_ID" ]; then
      grep "$YEAR" "$LOG_FILE" | awk -F'|' '{print $6, $7}' | sort | uniq -c | sort -rn
    else
      grep "$YEAR" "$LOG_FILE" | grep "|$AUDIO_ID|" | wc -l
    fi
    ;;
  *)
    echo "Usage: $0 {day|week|month|year} [audio_id]"
    exit 1
    ;;
esac
