#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

int main(void) {
    // Set real and effective UID to root
    if (setuid(0) != 0) {
        perror("setuid failed - is the setuid bit set?");
        return 1;
    }

    // Sync filesystems first (recommended before dropping caches)
    sync();

    // Open drop_caches
    int fd = open("/proc/sys/vm/drop_caches", O_WRONLY);
    if (fd < 0) {
        perror("Failed to open /proc/sys/vm/drop_caches");
        return 1;
    }

    // Write "1" to drop pagecache (sufficient for Postgres testing)
    // Use "3" for pagecache + dentries + inodes (cold start testing)
    if (write(fd, "1", 1) != 1) {
        perror("Failed to write to drop_caches");
        close(fd);
        return 1;
    }

    close(fd);
    printf("Filesystem caches purged successfully.\n");
    return 0;
}
