#include <stdio.h>
#include <string.h>
#include <qick.h>

void
usage(void)
{
	fprintf(stderr, "usage:    qdemo [server hostname] [server hostname2 ...] policy-statement\n");
	fprintf(stderr, "     or:  qdemo -c \"[server ...] policy-statement\"\n");
	fprintf(stderr, "policies: [[not] {default | field regex}] [{and|or} ...]\n");
	fprintf(stderr, "      or: {postfix|pf} [default | link policy] [field = value] [field ~ regex]\n");
	fprintf(stderr, "          [and | or | xor | not] ...\n");
	fprintf(stderr, "example:  qdemo server ns server alumni default and not tipoff . \\\n");
	fprintf(stderr, "          or type \"person: admin\" or appointment president\n");
	fprintf(stderr, "     or:  qdemo server ns server alumni link default tipoff ~ . not \\\n");
	fprintf(stderr, "          type = \"person: admin\" or appointment ~ /president/ or\n");
}

main(int argc, char *argv[])
{
	qick_t	*root;			/* world anchor */
	qi_t	*qi;			/* some server */
	qip_t	*policy;		/* my personal policy */
	qit_t	*qt;			/* temporary policy term */
	qir_t	*reply;			/* replies from server */
	char	 buf[512];
	int	 i, servers = 0;
	int	 wc;
	char	**wv;

	root = qick_init();		/* initialize all */
	if (root == NULL) {
		printf("no qi library?");
		exit(2);
	}

	/* Reparse argv[2] as the whole argv? */
	if (argc == 3 && !strcmp(argv[1], "-c")) {
		wc = qip_split(&wv, argv[2]);
		i = 0;
	} else {
		wc = argc;
		wv = argv;
		i = 1;
	}

	/* make up a policy */
	for (; i < wc; ++i) {

		if (!strcasecmp(wv[i], "-h")) {
			usage();
			exit(1);

		} else if (!strcasecmp(wv[i], "server")) {
			if (wc - i < 2) {
				usage();
				exit(2);
			}
			qi_server(root, wv[++i]);
			++servers;
			continue;

		} else if (!strcasecmp(wv[i], "postfix") ||
			   !strcasecmp(wv[i], "pf")) {
			++i;
			policy = qip_parse(root, "my_policy",
						wc-i, &wv[i]);
			i = wc;
		} else {
			policy = qip_parse_simple(root, "my_policy",
						wc-i, &wv[i]);
			i = wc;
		}
	}
	/* voila */

	/* if no servers named, add a default server to dynamic list */
	if (!servers) {
		qi_server(root, "ns");
		++servers;
	}


	while (1) {
		printf("query who> ");
		if (fgets(buf, 511, stdin) == NULL)
			break;
		buf[strlen(buf)-1] = '\0';	/* chomp */
		reply = qi_lookup(root, "query %s return all",
				buf);
		if (reply == NULL) {
			printf("no person named \"%s\"\n", buf);
			continue;
		}
		if (policy == NULL) {
			printf("No policy\n");
		} else if (qip_exec(policy, reply)) {
			printf("%s (%s) qualifies\n",
				buf, S(qi_field(reply, "name")));
		} else {
			printf("%s (%s) does not qualify\n",
				buf, S(qi_field(reply, "name")));
		}
		qir_free(reply);
	}
}

