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

void win(void) {
    char flag[128];
    FILE *f = fopen("flag.txt", "r");
    if (!f) {
        puts("[win] flag file not found");
        return;
    }
    if (fgets(flag, sizeof(flag), f)) {
        printf("FLAG: %s", flag);
    }
    fclose(f);
}

void chirp(void) {
    char tweet[48];

    puts("Tweet something cute (the canary is listening):");
    if (read(0, tweet, sizeof(tweet) - 1) <= 0) {
        puts("The canary looks away.");
        return;
    }
    tweet[sizeof(tweet) - 1] = '\0';

    printf("~ ");
    printf(tweet);
    puts("");
}

void nest(void) {
    char perch[64];

    puts("Climb onto the perch:");
    read(0, perch, 0x120);
    puts("The canary nods happily.");
}

void menu(void) {
    puts("");
    puts("  === Cute Canary ===");
    puts("  1) Chirp at the canary");
    puts("  2) Rest on the perch");
    puts("  3) Leave");
    printf("> ");
    fflush(stdout);
}

int main(void) {
    setvbuf(stdout, NULL, _IONBF, 0);
    setvbuf(stdin, NULL, _IONBF, 0);

    puts("A fluffy stack canary guards this nest.");

    while (1) {
        menu();

        char choice[8];
        if (!fgets(choice, sizeof(choice), stdin)) {
            break;
        }

        if (choice[0] == '1') {
            chirp();
        } else if (choice[0] == '2') {
            nest();
        } else if (choice[0] == '3') {
            puts("Bye!");
            break;
        } else {
            puts("?");
        }
    }

    return 0;
}