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

#include <sys/types.h>
#include <sys/socket.h>

#include <linux/ax25.h>

#include "config.h"

int main(int argc, char *argv[])
{
	struct full_sockaddr_ax25 dest;
	struct full_sockaddr_ax25 src;
	int s, n, dlen, len, interval = 30, port = 0;
	
	if (ax25_config_load_ports() == -1) {
		fprintf(stderr, "beacon: no AX.25 ports defined\n");
		return 1;
	}

	while ((n = getopt(argc, argv, "p:t:")) != -1) {
		switch (n) {
			case 'p':
				port = atoi(optarg) - 1;
				if (port < 0 || port >= ax25_config_num_ports()) {
					fprintf(stderr, "beacon: invalid AX.25 port setting\n");
					return 1;
				}
				break;
			case 't':
				interval = atoi(optarg);
				if (interval < 1) {
					fprintf(stderr, "beacon: interval must be greater than on minute\n");
					return 1;
				}
				break;
			case '?':
			case ':':
				fprintf(stderr, "usage: beacon [-p <port>] [-t <interval>] message\n");
				return 1;
		}
	}

	if (optind == argc) {
		fprintf(stderr, "usage: beacon [-p <port>] [-t <interval>] message\n");
		return 1;
	}
	
	dlen = convert_call("IDENT", &dest);
		
	if ((len = convert_call(ax25_config_get_addr(port), &src)) == -1) {
		fprintf(stderr, "beacon: unable to convert callsign '%s'\n", ax25_config_get_addr(port));
		return 1;
	}

	for (;;) {
		if ((s = socket(AF_AX25, SOCK_DGRAM, 0)) == -1) {
			perror("socket");
			return 1;
		}

		if (bind(s, (struct sockaddr *)&src, len) == -1) {
			perror("bind");
			return 1;
		}
		
		if (sendto(s, argv[optind], strlen(argv[optind]), 0, (struct sockaddr *)&dest, dlen) == -1) {
			perror("sendto");
			return 1;
		}

		close(s);

		sleep(interval * 60);
	}

	return 0;
}
