#!/usr/bin/perl

{ use 5.006; }
use warnings;
use strict;

use Date::JD 0.005 qw(cjdn_to_mjdnn);
use Date::ISO8601 0.000 qw(ymd_to_cjdn present_ymd);
use Digest::SHA 3.0 qw(sha1);
use Getopt::Std 1.02 qw(getopts);
use IO::Handle 1.21 ();
use MIME::Base64 2.21 qw(decode_base64 encode_base64);
use Math::BigInt 1.64 ();

sub z($) {
	my($s) = @_;
	return $s >= 0 ? $s * 2 : $s * -2 - 1;
}

sub unz($) {
	my($u) = @_;
	return $u->is_even ? $u / 2 : ($u + 1) / -2;
}

my $zero = Math::BigInt->new(0);
my $mjdn_of_cjdn0 = cjdn_to_mjdnn(0, 0, 0);

sub gen_bin_uint($) {
	my($u) = @_;
	my $ones = 0;
	my $bytes = "";
	my $bits = 0;
	my $nbits = 0;
	while(1) {
		$bits |= (($u & 0x7f)->numify) << $nbits;
		$nbits += 7;
		if($nbits >= 8) {
			$bytes .= chr($bits & 0xff);
			$bits >>= 8;
			$nbits -= 8;
		}
		last if $u < 0x80;
		$u = ($u >> 7) - 1;
		$ones++;
	}
	return ("\xff" x ($ones >> 3)) . chr(($bits | (0xfe<<$nbits)) & 0xff) .
		reverse($bytes);
}

sub gen_bin_body($) {
	my($seg) = @_;
	@$seg or return gen_bin_uint($zero);
	my $bytes = gen_bin_uint(z($seg->[0]->{first_mjdn}) + 1) .
		gen_bin_uint(z($seg->[0]->{offset})) .
		gen_bin_uint($seg->[0]->{last_mjdn} - $seg->[0]->{first_mjdn});
	for(my $i = 1; $i != @$seg; $i++) {
		if($seg->[$i]->{first_mjdn} != $seg->[$i-1]->{last_mjdn} + 1) {
			$bytes .= gen_bin_uint(1+z($zero)) .
				gen_bin_uint($seg->[$i]->{first_mjdn} -
					$seg->[$i-1]->{last_mjdn} - 2) .
				gen_bin_uint(z($seg->[$i]->{offset} -
					$seg->[$i-1]->{offset}));
		} else {
			$bytes .= gen_bin_uint(1+z($seg->[$i]->{offset} -
					$seg->[$i-1]->{offset}));
		}
		$bytes .= gen_bin_uint($seg->[$i]->{last_mjdn} -
					$seg->[$i]->{first_mjdn});
	}
	return $bytes . gen_bin_uint($zero);
}

sub gen_check($) {
	my($body) = @_;
	return sha1("\xd4\x22\x05\xfe\x06\xa6\x59\xb2" . $body);
}

sub gen_bin_file($) {
	my($seg) = @_;
	my $body = gen_bin_body($seg);
	return "\xe9\x9b\xfe\xc0\x32\x36\xe9\xe5" . $body . gen_check($body);
}

sub read_bytes($$) {
	my($fh, $len) = @_;
	my $data;
	my $rlen = $fh->read($data, $len);
	defined $rlen or die "can't read Lemaitre file: $!";
	$rlen == $len or die "bad Lemaitre file: premature EOF";
	return $data;
}

sub read_bin_uint($) {
	my($fh) = @_;
	my $ones = 0;
	my($bits, $nbits);
	do {
		$bits = ord(read_bytes($fh, 1));
		$nbits = 7;
		while($nbits >= 0 && ($bits & (1 << $nbits))) {
			$nbits--;
			$ones++;
		}
	} while($nbits < 0);
	$bits &= (1 << $nbits) - 1;
	my $u = Math::BigInt->new(-1);
	do {
		if($nbits < 7) {
			$bits = ($bits << 8) | ord(read_bytes($fh, 1));
			$nbits += 8;
		}
		$bits &= (1 << $nbits) - 1;
		$u = (($u + 1) << 7) | ($bits >> ($nbits - 7));
		$nbits -= 7;
	} while($ones--);
	return $u;
}

sub read_bin_body($) {
	my($fh) = @_;
	my $u = read_bin_uint($fh);
	return [] if $u == 0;
	my @seg = ({
		first_mjdn => unz($u-1),
		offset => unz(read_bin_uint($fh)),
	});
	while(1) {
		$seg[-1]->{last_mjdn} =
			$seg[-1]->{first_mjdn} + read_bin_uint($fh);
		$u = read_bin_uint($fh);
		return \@seg if $u == 0;
		if($u == 1+z($zero)) {
			$u = read_bin_uint($fh);
			push @seg, {
				first_mjdn => $seg[-1]->{last_mjdn} + 2 + $u,
				offset => $seg[-1]->{offset} +
						unz(read_bin_uint($fh)),
			};
		} else {
			push @seg, {
				first_mjdn => $seg[-1]->{last_mjdn} + 1,
				offset => $seg[-1]->{offset} + unz($u-1),
			};
		}
	}
}

sub read_bin_file($) {
	my($fh) = @_;
	read_bytes($fh, 8) eq "\xe9\x9b\xfe\xc0\x32\x36\xe9\xe5" or
		die "bad Lemaitre file: bad magic";
	my $seg = read_bin_body($fh);
	read_bytes($fh, 20) eq gen_check(gen_bin_body($seg)) or
		die "bad Lemaitre file: check field mismatch";
	return $seg;
}

sub read_line($) {
	my($fh) = @_;
	my $line = $fh->getline;
	!$fh->error or die "can't read Lemaitre file: $!";
	defined($line) && $line =~ s/\n\z// or
		die "bad Lemaitre file: premature EOF";
	return $line;
}

sub parse_date($) {
	my($str) = @_;
	my($y, $m, $d) = ($str =~ /\A
		(-?[0-9]{4}|[\-\+][1-9][0-9]{4,})-([0-9]{2})-([0-9]{2})
	\z/x);
	defined($y) && $y ne "-0000" or die "bad Lemaitre file: malformed date";
	return ymd_to_cjdn(Math::BigInt->new($y), $m, $d) + $mjdn_of_cjdn0;
}

sub read_text_file($) {
	my($fh) = @_;
	read_line($fh) eq "q_M=+d&./=" or die "bad Lemaitre file: bad magic";
	my $line;
	my @seg;
	while(1) {
		$line = read_line($fh);
		my($sdate, $edate, $offset) = ($line =~ m#\A
			([\-\+0-9]+)/([\-\+0-9]+)\ (\+0|[\-\+][1-9][0-9]*)
		\z#x);
		defined $sdate or last;
		push @seg, {
			first_mjdn => parse_date($sdate),
			last_mjdn => parse_date($edate),
			offset => Math::BigInt->new($offset),
		};
		$seg[-1]->{last_mjdn} >= $seg[-1]->{first_mjdn} or
			die "bad Lemaitre file: ".
				"segment extends backwards in time";
		if(@seg >= 2) {
			$seg[-1]->{first_mjdn} >= $seg[-2]->{first_mjdn} or
				die "bad Lemaitre file: ".
					"segments out of sequence";
			$seg[-1]->{first_mjdn} > $seg[-2]->{last_mjdn} or
				die "bad Lemaitre file: segments overlap";
			if($seg[-1]->{first_mjdn} == $seg[-2]->{last_mjdn}+1) {
				$seg[-1]->{offset} != $seg[-2]->{offset} or
					die "bad Lemaitre file: ".
						"abutting segments have ".
						"identical offset";
			}
		}
	}
	if($line =~ m#\A:([A-Za-z0-9\+\/]{26}[AEIMQUYcgkosw048])\z#) {
		decode_base64($1."=") eq gen_check(gen_bin_body(\@seg)) or
			die "bad Lemaitre file: check field mismatch";
	} elsif($line ne ".") {
		die "bad Lemaitre file: malformed line";
	}
	return \@seg;
}

sub gen_text_date($) {
	my($mjdn) = @_;
	return present_ymd($mjdn - $mjdn_of_cjdn0);
}

sub gen_text_offset($) {
	my($o) = @_;
	my $str = "$o";
	$str =~ s/\A(?=[0-9])/+/;
	return $str;
}

sub gen_text_file($$) {
	my($seg, $with_check) = @_;
	return join("", "q_M=+d&./=\n",
		(map {
			gen_text_date($_->{first_mjdn}) . "/" .
			gen_text_date($_->{last_mjdn}) . " " .
			gen_text_offset($_->{offset}) . "\n"
		} @$seg),
		($with_check ? do {
			my $check_b64 =
				encode_base64(gen_check(gen_bin_body($seg)),
						"");
			$check_b64 =~ s/\=\z//;
			":$check_b64\n";
		} : ".\n"),
	);
}

sub usage {
	STDERR->print("usage: $0 [ -c | -b | -t | -e ] [ <input-file> ]\n");
	exit 2;
}

my %opts;
getopts("cbte", \%opts) or usage;
(grep { $opts{$_} } qw(c b t e)) <= 1 or usage;
@ARGV <= 1 or usage;

if(@ARGV == 1 && $ARGV[0] ne "-") {
	open(STDIN, "<", $ARGV[0]) or die "can't open $ARGV[0]: $!";
}
my $c = read_bytes(\*STDIN, 1);
STDIN->ungetc(ord($c));
my $seg = $c eq "q" ? read_text_file(\*STDIN) : read_bin_file(\*STDIN);
{
	my $rlen = STDIN->read(my $d, 1);
	defined $rlen or die "can't read Lemaitre file: $!";
	$rlen == 0 or die "bad Lemaitre file: extraneous content before EOF";
}

unless($opts{c}) {
	my $output = $opts{b} ? gen_bin_file($seg) :
		$opts{e} ? gen_text_file($seg, 0) : gen_text_file($seg, 1);
	STDOUT->printflush($output) or die "can't write Lemaitre file: $!";
}

exit 0;

=head1 NAME

convert_lemaitre - convert between the Lemaitre file formats

=head1 SYNOPSIS

    convert_lemaitre [ -c | -b | -t | -e ] [ <input-file> ]

=head1 DESCRIPTION

B<Caution: this program is based on a draft of the Lemaitre file format
specification.>

This program is concerned with the Lemaitre file formats, which are
used to represent the leap second schedule of a UTC-like time scale.
It takes as input a file in either of the Lemaitre formats (textual or
binary), and generates as output an equivalent file in either format.
Along the way it checks the validity of the input file; it will signal
an error and not generate output if the input is invalid.

The input file is taken from the file specified on the command line.
If the filename given is "B<->", or if no filenmae is given, input is
taken from standard input.  The output is written to standard output.

=head1 OPTIONS

=over

=item B<-b>

Output in the binary Lemaitre file format.

=item B<-c>

Check input only: do not produce any output.

=item B<-e>

Output in the textual Lemaitre file format, with no check field.
This should only be used when the output file is to be edited by a human.

=item B<-t>

Output in the textual Lemaitre file format, including check field.
This is the default action.

=back

=head1 SEE ALSO

L<lemaitre(5)>

=head1 AUTHOR

Andrew Main (Zefram) <zefram@fysh.org>
