#include "iftun.h"
#include "extremite.h"

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


char *dev;
char *inip;
char *outip;
int inport;
int outport;


int main(int argc, char *argv[argc]) {
	if (argc != 2) {
		fprintf(stderr, "Utilisation : %s fichier_conf\n", argv[0]);
	}
	if (getuid() != 0) {
		fprintf(stderr, "%s doit être lancé en tant que superutilisateur.\n", argv[0]);
		return 1;
	}

	FILE *f = fopen(argv[1], "r");

	char *line = NULL;
	size_t n = 0;
	ssize_t len;
	while ((len = getline(&line, &n, f)) > 0) {
		char *pair = strtok(line, "#");
		char *key = strtok(pair, "=");
		char *val = strtok(NULL, "=");
		if (val != NULL) {
			line[len-1] = '\0';
			printf("%s=%s\n", key, val);
			if (strcmp(key, "tun") == 0) {
				dev = malloc(strlen(val));
				strcpy(dev, val);
			}
			else if (strcmp(key, "inip") == 0) {
				inip = malloc(strlen(val) + 1);
				strcpy(inip, val);
			}
			else if (strcmp(key, "outip") == 0) {
				outip = malloc(strlen(val) + 1);
				strcpy(outip, val);
			}
			else if (strcmp(key, "inport") == 0) {
				inport = atoi(val);
			}
			else if (strcmp(key, "outport") == 0) {
				outport = atoi(val);
			}
		}
	}
	if (line) free(line);
	fclose(f);

	int tun = tun_alloc(dev);

	char full_cmd[1024] = "";
	sprintf(full_cmd, "./configure-tun.sh %s %s", dev, inip);
	if (system(full_cmd) != 0) {
		fprintf(stderr, "Erreur lors de l’exécution du script de configuration de l’interface.\n");
		return 1;
	}
	ext_bidir(outip, outport, inport, tun, tun);

	return 0;
}
