summaryrefslogtreecommitdiff
path: root/junker.sh
blob: 28fdf1a8a5b5587ad097e7649a524b22bb70c6e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/bin/bash

[ ! -z "${DEBUG}" ] && set -x

BASE=$1
INOTIFY='/usr/bin/inotifywait'
INOTIFY_EVENTS='close_write,moved_to'
INOTIFY_OPTIONS='--monitor --recursive --event'" ${INOTIFY_EVENTS}"
SALEARN=/usr/bin/sa-learn
SAOPTS=--no-sync
LOGS=$2

function OpenLog {
    exec 3>>"${LOGS}/junker.log"
    exec 1>&3
    exec 2>&3
    echo -e "$( date +'%Y%m%d %H:%M:%S' )\tLog opened"
}
function CloseLog {
    echo -e "$( date +'%Y%m%d %H:%M:%S' )\tLog closed"
    exec 3>&-
}

function Cleanup {
    RunAndLog echo ${SALEARN} --sync
    CloseLog
    exit 0
}

function RunAndLog {
    echo -e "$( date +'%Y%m%d %H:%M:%S' )\t$@"
    $@
}

function Reload {
    CloseLog
    OpenLog
}

OpenLog

trap "Cleanup" EXIT SIGINT SIGTERM
trap "Reload" SIGHUP

while IFS='	' read -r dir event file
do
    if [[ "${event}" == *MOVED_TO* && "${dir}" == */Junk/ ]]
    then
        RunAndLog echo ${SALEARN} ${SAOPTS} --forget "${dir}/${file}"
        RunAndLog echo ${SALEARN} ${SAOPTS} --spam "${dir}/${file}"
    elif [[ "${event}" == *MOVED_TO* && "${dir}" == */!Junk/ ]]
    then
        RunAndLog echo ${SALEARN} ${SAOPTS} --forget "${dir}/${file}"
        RunAndLog echo ${SALEARN} ${SAOPTS} --ham "${dir}/${file}"
    elif [[ "${event}" == *CLOSE_WRITE* && "${dir}" == */Junk/ ]]
    then
        RunAndLog echo ${SALEARN} ${SAOPTS} --spam "${dir}/${file}"
    else
        RunAndLog echo ${SALEARN} ${SAOPTS} --ham "${dir}/${file}"
    fi
done < <( ${INOTIFY} ${INOTIFY_OPTIONS} --format '%w	%e	%f' ${BASE} )