/*
*   gcc del_ext.c -o del_ext -O2 -Wall -s
*/

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <ftw.h>


#define DOT '.'


static char *ext = NULL;
static unsigned long long num_deleted = 0;
static unsigned long long num_skipped = 0;


static void exit_with_message(int err, const char *message, ...) {
    va_list va;
    va_start(va, message);
    vprintf(message, va);
    va_end(va);
    exit(err);
}

static int remove_ext_cb(const char *fpath, const struct stat *_st, int type, struct FTW *_ftw) {
    char *tmp;
    if (type == FTW_F) {
        if ((tmp = strrchr(fpath, DOT)) && strcmp(tmp, ext) == 0) {
            num_deleted++;
            return remove(fpath);
        }
        else {
            num_skipped++;
        }
    }
    return 0;
}

int main(int argc, char **argv) {
    printf("welcome\n");

    if (argc < 2) {
        exit_with_message(EXIT_FAILURE, "missing args: location .ext\n");
    }

    if (!(ext = strchr(argv[2], '.')) || strlen(ext) < 2) {
        exit_with_message(EXIT_FAILURE, "%s is not an extension, eg .json\n", argv[2]);
    }

    int ret = nftw(argv[1], remove_ext_cb, 64, FTW_DEPTH | FTW_PHYS);

    printf("\n---finished---\n\nfiles removed: %llu\nfiles skipped: %llu\nerror code: %d\n",
        num_deleted, num_skipped, ret);

    return ret;
}