#!/usr/bin/env perl -w

# This script generates licence.h (containing the PuTTY licence in the
# form of macros expanding to C string literals) from the LICENCE
# master file.

use File::Basename;

$infile = "LICENCE";
$outfile = "licence.h";
open my $in, $infile or die "$infile: open: $!\n";
open my $out, ">", $outfile or die "$outfile: open: $!\n";
select $out;

print "/*\n";
print " * $outfile - macro definitions for the PuTTY licence.\n";
print " *\n";
print " * Generated by @{[basename __FILE__]} from $infile.\n";
print " * You should edit those files rather than editing this one.\n";
print " */\n";
print "\n";

my @lines = ();
while (<$in>) {
    chomp;
    push @lines, $_;
}
close $in;

# Format into paragraphs.
my @paras = ();
my $para = undef;
for my $line (@lines) {
    if ($line eq "") {
        $para = undef;
    } elsif (!defined $para) {
        push @paras, $line;
        $para = \$paras[$#paras];
    } else {
        $$para .= " " . $line;
    }
}

print "#define LICENCE_TEXT(parsep) \\\n";
for my $i (0..$#paras) {
    my $lit = &stringlit($paras[$i]);
    print "    parsep \\\n" if $i > 0;
    print "    \"$lit\"";
    print " \\" if $i < $#paras;
    print "\n";
}
print "\n";

die "bad format of first paragraph\n"
    unless $paras[0] =~ m!copyright ([^\.]*)\.!i;

printf "#define SHORT_COPYRIGHT_DETAILS \"%s\"\n", &stringlit($1);

sub stringlit {
    my ($lit) = @_;
    $lit =~ s!\\!\\\\!g;
    $lit =~ s!"!\\"!g;
    return $lit;
}
