aboutsummaryrefslogtreecommitdiff
path: root/cleanup.c
blob: 429c8c26535aefc2e0ef6ee41727a61effcca45e (plain) (blame)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
 * Copyright 2020 Ryan Kavanagh <rak@rak.ac>
 * Cleanup hosted temporary files
 *
 * Permission to use, copy, modify, and/or distribute this software for
 * any purpose with or without fee is hereby granted, provided that the
 * above copyright notice and this permission notice appear in all
 * copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
 * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
 * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
 * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <fts.h>

#include <err.h>
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>

const double mind = 30.0;
const double maxd = 90.0;
const double max_size = 33554432; // 32MB
char* paths[2] = {"/var/www/users/~tmp", NULL};

int
main(int argc, char * const argv[])
{
	FTS* file_system;
	FTSENT* node;
	struct stat attr;

	double cutoff = 0;
	double file_age = 0;
	time_t curr_time = time(NULL);

	int verbose, ch;

	verbose = 0;
	while ((ch = getopt(argc, argv, "v")) != -1) {
		switch (ch) {
		case 'v':
			verbose = 1;
			break;
		}
	}
	argc -= optind;
	argv += optind;

	if ((file_system = fts_open(paths, 0, NULL)) == NULL)
		errx(1, NULL);

	while ((node = fts_read(file_system)) != NULL) {
		if (node->fts_errno)
			err(node->fts_errno, "%s", node->fts_path);

		switch (node->fts_info) {
		case FTS_F:
			if (stat(node->fts_name, &attr) == -1)
				err(1, NULL);
			file_age = difftime(curr_time, attr.st_mtime);
			cutoff = mind + (mind - maxd) * 86400 *
				pow((double) attr.st_size / (double) max_size - 1, 3.0);
			if (verbose)
				printf("%s age %fs cuttoff %fs size %lldB\n",
				       node->fts_name, file_age, cutoff, attr.st_size);
			if (file_age >= cutoff) {
				unlink(node->fts_name);
				if (verbose)
					printf("%s deleted\n", node->fts_name);
			}
			break;
		default:
			break;
		}
	}

	fts_close(file_system);


	return 0;
}