#!/bin/zsh ## syntax: $0 [-g] [-a] [-d|-D] [-p start_day] [month] [year] # -g gnuplot graphics # -a all processed entries # -d group by day # -D day and detailed entry # -p set invoice period starting from start_day # month traffic of month # year self=$(readlink -f =$0) if [[ $1 == -h ]] { eval "</dev/null| grep '^Total')" plot "<$self $@ 2>/dev/null | sed -re's/-[[:digit:]]{3}: /_/' | sed -re's/[[:digit:]]{4}-([[:digit:]]{2})-([[:digit:]]{2})(_[[:digit:]]{2}:[[:digit:]]{2}:[[:digit:]]{2}|:)/\\\\2/' | grep -v '^Total'" using (\$2/1024/1024):xtic(1) w boxes title "bw usage", '' u 0:(\$2/1024/1024):3 w labels off 0,1 not GNUPLOT } pushd -q $self:h ((year=$(date +%Y))) ((month=$(date +%m))) ((period_from=10)) if [[ $1 == -a ]] { output_all==true; shift } \ else { output_all==false } if [[ $1 == -d ]] { show_day_traffic==true; show_name_traffic==false; shift } \ elif [[ $1 == -D ]] { show_day_traffic==true; show_name_traffic==true; shift } \ else { show_day_traffic==false; show_name_traffic==true; } if [[ $1 == -p && -n $2 ]] { ((period_from=$2)) && shift; shift } [[ -n $1 ]] && ((month=$1)) && shift [[ -n $1 ]] && ((year=$1)) && shift ((day=$(date +%d))) if [[ $day -lt $period_from ]] { ((--month)) if [[ $month -lt 1 ]] { ((month=12)); ((--year)) } } typeset -U users ((current_count=0)) for loop (1 2) { echo "calculating month $month $year from $period_from" >&2 setopt nullglob; stats_files=($year-$(printf %02d $month)-<->); unsetopt nullglob for stats ($stats_files) { ((stats_for_day=$(echo $stats|cut -f3 -d-))) echo "processing $stats" >&2 tempdir=$(mktemp -d ./$stats.splits.XXXXX) csplit -f $tempdir/ -n 3 -z $stats /======/ '{*}' >&2 setopt nullglob; connect_files=($tempdir/<->); unsetopt nullglob ((day_traffic=0)) for connects ($connect_files) { ts=$(echo $stats-$connects:t: $(head -1 $connects|sed -re's/=*.*[[:space:]]([[:digit:]]+:[[:digit:]]+:[[:digit:]]+)[[:space:]].*=*/\1/')) for line ($(grep HomeTrafficInBytes $connects)) { user=$(echo $line|cut -f2 -d/) traffic=$(echo $line|cut -f2 -d=) users+=($user) ((this_traffic=traffic-traffic_count_$user)) ((traffic_count_$user=$traffic)) output_l==false if [[ ( $stats_for_day -ge $period_from && $loop -eq 1 ) \ || ( $stats_for_day -lt $period_from && $loop -eq 2 ) ]] { output_l==true ((total_traffic+=this_traffic)) } ((day_traffic+=this_traffic)) if ( $show_name_traffic ) { if ( $output_l || $output_all ) { if [[ $this_traffic -gt 0 ]] { echo $ts$'\t'$this_traffic$'\t'"($user)" } } } } } output_l==false if [[ ( $stats_for_day -ge $period_from && $loop -eq 1 ) \ || ( $stats_for_day -lt $period_from && $loop -eq 2 ) ]] { output_l==true } if ( $show_day_traffic ) { if ( $output_l || $output_all ) { if [[ $day_traffic -gt 0 ]] { echo $stats:$'\t'$day_traffic } } } rm -r $tempdir } if [[ $loop -eq 1 ]] { ((++month)) [[ $month -gt 12 ]] && { ((month=1)); ((++year)) } for user ($users) { ((traffic_count_$user=0)) } } } echo "Total before $month $period_from $year: $total_traffic"$'\t' popd -q