#!/usr/bin/perl
#
# Generate lwlocknames.h and lwlocknames.c from lwlocknames.txt
# Copyright (c) 2000-2016, PostgreSQL Global Development Group

use warnings;
use strict;

my $lastlockidx = -1;
my $continue    = "\n";

open my $lwlocknames, $ARGV[0] or die;

# Include PID in suffix in case parallel make runs this multiple times.
my $htmp = "lwlocknames.h.tmp$$";
my $ctmp = "lwlocknames.c.tmp$$";
open H, '>', $htmp or die "Could not open $htmp: $!";
open C, '>', $ctmp or die "Could not open $ctmp: $!";

my $autogen =
"/* autogenerated from src/backend/storage/lmgr/lwlocknames.txt, do not edit */\n";
print H $autogen;
print H "/* there is deliberately not an #ifndef LWLOCKNAMES_H here */\n\n";
print C $autogen, "\n";

print C "char *MainLWLockNames[] = {";

while (<$lwlocknames>)
{
	chomp;

	# Skip comments
	next if /^#/;
	next if /^\s*$/;

	die "unable to parse lwlocknames.txt"
	  unless /^(\w+)\s+(\d+)$/;

	(my $lockname, my $lockidx) = ($1, $2);

	die "lwlocknames.txt not in order"   if $lockidx < $lastlockidx;
	die "lwlocknames.txt has duplicates" if $lockidx == $lastlockidx;

	while ($lastlockidx < $lockidx - 1)
	{
		++$lastlockidx;
		printf C "%s	\"<unassigned:%d>\"", $continue, $lastlockidx;
		$continue = ",\n";
	}
	printf C "%s	\"%s\"", $continue, $lockname;
	$lastlockidx = $lockidx;
	$continue    = ",\n";

	print H "#define $lockname (&MainLWLockArray[$lockidx].lock)\n";
}

printf C "\n};\n";
print H "\n";
printf H "#define NUM_INDIVIDUAL_LWLOCKS		%s\n", $lastlockidx + 1;

close H;
close C;

rename($htmp, 'lwlocknames.h') || die "rename: $htmp: $!";
rename($ctmp, 'lwlocknames.c') || die "rename: $ctmp: $!";

close $lwlocknames;
