#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>

void read_knock(char* path) {
    FILE* f = fopen(path, "r");
    fgetc(f);
    fclose(f);
    usleep(50000);
}

bool file_exists(char* path) {
    return access(path, F_OK) != -1;
}

bool knock(int door) {
    char path[64];
    sprintf(path, "challenge/%d", door);

    if (!file_exists(path)) {
        // printf("doesn't exist, skipping...\n");
        return false;
    }

    // printf("knocking door %d...\n", door);
    FILE* f = fopen(path, "a");
    fputc(42, f);
    fclose(f);

    usleep(100000);
    return true;
}

int main() {
    int seq[10];
    int index = 0;
    
    while (!file_exists("challenge/flag")) {
        for (int i = 0; i < 10; i++) {
            if (!knock(i)) continue;

            if (file_exists("challenge/message")) {
                read_knock("challenge/message");

                for (int j = 0; j < index; j++) {
                    knock(seq[j]);
                }

                continue;
            }

            seq[index++] = i;
            printf("%d\n", i);
            break;
        }
    }

    read_knock("challenge/flag");
    read_knock("challenge/message");

    for (int j = 0; j < index; j++) {
        knock(seq[j]);
    }
}