#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#define VALID_CHARS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_"
#define COMPOSE "/usr/local/bin/docker-compose"

/* Just check only allowed chars are present */
int validate (char *s) {
    for (int i=0; i<strlen(s); i++){
        int found = 0;
        for (int j=0; j<strlen(VALID_CHARS); j++) {
            if ( s[i] == VALID_CHARS[j] ) {
                found = 1;
                break;
            }
        }
        if (!found) {
            return 1;
        }
    }
    return 0;
}

void usage () {
	printf("Usage: compose_logs <compose_dir> <instance>|list <since> <until>\n");
}

int is_line_in_file (char* l, char* filename) {
    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;

    fp = fopen(filename, "r");
    if (fp == NULL) {
		return 1;
	}

    while ((read = getline(&line, &len, fp)) != -1) {
		if (line[len-1] == '\n') {
			line[len-1] = '\0';
		}
        printf("Retrieved line of length %zu:\n", read);
		printf("len(l)=%zu\n", strlen(l));
		printf("mdr %d\n", '\n');
		for (int i=0; i<len; i++) {
			printf("lol l    %d : %d\n", i, l[i]);
			printf("lol line %d : %d\n", i, line[i]);
		}
        printf("%s", line);
		if (strcmp(line, l) == 0) {
			free(line);
    		fclose(fp);
			return 0;
		}
    }

    fclose(fp);
    if (line)
        free(line);
	return 1;
}


/* Main program. */

int
main (int argc, char* argv[])
{
	if (argc < 3 ) {
		usage();
		exit(1);
	}

	/* Chdir */
	if (chdir(argv[1]) != 0) {
    	printf("chdir() to /usr failed");
		exit(1);
	}

    if (validate(argv[2]) != 0) {
        printf("Bad service name\n");
        exit(1);
    }

	if (is_line_in_file("33", "allow_docker_logs") != 0) {
		printf("unauthorized\n");
		exit(1);
	}

	/* List mode */
	if (strcmp(argv[2],"list") == 0) {
		if (execl(COMPOSE, COMPOSE, "ps", "--format", "json", (char *)NULL) == -1) {
			printf("Error exec docker-compose ps\n");
			printf("%s\n", strerror(errno));
			exit(1);
		}
	/* log mode */
	} else {
		if (argc < 5 ) {
			usage();
			exit(1);
		}

		if (execl(COMPOSE, COMPOSE, "logs", argv[2], "--since", argv[3], "--until", argv[4], (char *)NULL) == -1) {
			printf("Error exec docker-compose logs\n");
			printf("%s\n", strerror(errno));
			exit(1);
		}
	}
}

