#!/bin/bash
# copyright 2012 Daniil Baturin <daniil@baturin.org>
# Mail yesterday irssi logs to watchers

LOG_DIR="/home/user/logs/Freenode"
LOG_FILES="##vyatta.log"
TMP_DIR=/tmp
WATCHERS="rec1@domain1 rec2@domain2"
DAYCHANGE_STR="--- Day changed .* "
DATE_FORMAT="%b %d %Y" # Jun 4 2012
EXCLUDE="^([0-9]{2}:[0-9]{2}\-!\-) " # Service messages
START=$(date -d yesterday +"$DATE_FORMAT")
END=$(date +"$DATE_FORMAT")

# Check if mutt is installed
if [ ! -x $(which mutt) ]; then
    echo "Error: mutt mail client is not installed!"
fi

for file in "$LOG_FILES"; do
    THIS=$LOG_DIR/$file
    START_LINE=$(cat -n "$THIS" | grep -e "$START" | awk -F ' ' '{print $1}')
    STOP_LINE=$(cat -n "$THIS" | grep -e "$END" | awk -F ' ' '{print $1}')
    LINES=$(wc -l "$THIS"|awk -F ' ' '{print $1}')
    TMP_FILE=$TMP_DIR/$file-$(date +%d%m)

    tail -n $(($LINES-$START_LINE+1)) "$THIS" | head -n $(($STOP_LINE-$START_LINE+1)) \
    | grep -vPe '^[0-9]{2}:[0-9]{2}-\!-' > $TMP_FILE

    LOG_NAME=$(echo $file | sed -e s/\\..*//)
    for address in $WATCHERS; do
       mutt -s "$LOG_NAME IRC log $(date +"%b %d %Y")" $address < $TMP_FILE
    done

   rm -f $TMP_FILE
done

