summaryrefslogtreecommitdiff
path: root/rolling-directory
blob: ce970215c2f7359351592aa7b09c50b463b0a1a2 (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
62
63
64
65
66
67
#!@zsh@/bin/zsh

set -e

PATH=@coreutils@/bin:@findutils@/bin:@gawk@/bin:@inotify@/bin:$PATH

dir=${1:A}
maxSize=$(numfmt --from=auto --to=none -- $2)
shift 2

[[ -d "${dir}" ]] || exit 2
[[ "${maxSize}" = <-> ]] || exit 2

typeset -a findExtra
findExtra=(-not -path ${dir}/CACHEDIR.TAG)

resize() {
    echo "Resizing ${dir} to below $(numfmt --to=iec-i --suffix=B -- ${maxSize})..." >&2

    while [[ $(du -xbs ${dir} | awk '{ print $1; }') -gt $maxSize ]]; do
        find ${dir} -xdev -type f \( ${findExtra} \) -print0 | \
            xargs -r0 -- stat --printf '%W %Y %Z %X %n\0' | \
            sort -t '\0' -z | \
            awk -F '\0' '{ gsub("^\\S+\\s+\\S+\\s+\\S+\\s+\\S+\\s+", "", $1); printf "%s\0", $1; }' | \
            xargs -r0 -- rm -v
    done

    find ${dir} -xdev -xtype l -print0 | xargs -r0 -- rm -v
    find ${dir} -xdev -type d \( -not -path ${dir} \) -empty -print0 | xargs -r0 -- rmdir -v
}

case "${1}" in
    monitor)
        shift

        sleep=""
        typeset -a inotifyExtra
        inotifyExtra=()

        while getopts 's:t:' opt; do
            case "${opt}" in
                s)
                    [[ "${OPTARG}" = <-> ]] || exit 2
                    sleep=${OPTARG}
                ;;
                t)
                    [[ "${OPTARG}" = <-> ]] || exit 2
                    inotifyExtra+=(-t "${OPTARG}")
            esac
        done
        
        while
            resize
            [[ -n "$sleep" ]] && sleep ${sleep}
            inotifywait -qq -r ${dir} ${inotifyExtra} \
                        -e modify \
                        -e close_write \
                        -e moved_to \
                        -e move_self \
                        -e create
            true
        do :; done
    ;;
    *)
        resize
    ;;
esac