#!/usr/bin/env perl
#
# Copyright (C) 2001-2021 Graeme Walker <graeme_walker@users.sourceforge.net>
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ===
#
# make2cdb
#
# Parses automake files throughout the source tree and generates
# a "compilation database" file, "compile_commands.json".
#
# See also: https://clang.llvm.org/docs/JSONCompilationDatabase.html
#
# Usage: make2cdb [--list] [<src-dir> [<top-dir> [<src-to-top>]]]
#
# Eg:
#  $ cd src
#  $ ../bin/make2cdb > compile_commands.json
#  $ ../bin/make2cdb --list | xargs clang-tidy -p .
#

use strict ;
use Cwd ;
use FileHandle ;
use File::Find ;
use File::Basename ;
use File::Spec ;
use File::Copy ;
use lib dirname($0) ;
use CompilationDatabase ;
$CompilationDatabase::debug = 0 ;

my $show_list = $ARGV[0] eq "--list" ;
shift @ARGV if $show_list ;

my $src_dir = @ARGV ? $ARGV[0] : dirname($0)."/../src" ;
my $top_dir = @ARGV >= 1 ? $ARGV[1] : "$src_dir/.." ;
my $src_to_top = @ARGV >= 2 ? $ARGV[2] : ".." ;

my @dflags = (
	"-DG_UNIX=1" ,
) ;

# makefile conditionals
my %switches = (
	GCONFIG_BSD => 0 ,
	GCONFIG_GUI => 0 ,
	GCONFIG_ICONV => 0 ,
	GCONFIG_INSTALL_HOOK => 0 ,
	GCONFIG_INTERFACE_NAMES => 1 ,
	GCONFIG_MAC => 0 ,
	GCONFIG_PAM => 0 ,
	GCONFIG_TESTING => 0 ,
	GCONFIG_TLS_USE_BOTH => 0 ,
	GCONFIG_TLS_USE_MBEDTLS => 0 ,
	GCONFIG_TLS_USE_NONE => 0 ,
	GCONFIG_TLS_USE_OPENSSL => 1 ,
	GCONFIG_WINDOWS => 0 ,
) ;

# makefile expansion variables -- many are required but not relevant
my %vars = (
	top_srcdir => $src_to_top ,
	top_builddir => "." ,
	sbindir => "." ,
	mandir => "." ,
	localedir => "." ,
	e_spooldir => "/var/spool/emailrelay" ,
	e_docdir => "." ,
	e_initdir => "." ,
	e_bsdinitdir => "." ,
	e_rundir => "." ,
	e_icondir => "." ,
	e_examplesdir => "." ,
	e_libexecdir => "." ,
	e_pamdir => "." ,
	e_sysconfdir => "/etc" ,
	GCONFIG_WINDRES => "" ,
	GCONFIG_WINDMC => "" ,
	GCONFIG_QT_LIBS => "" ,
	GCONFIG_QT_CFLAGS => "" ,
	GCONFIG_QT_MOC => "" ,
	GCONFIG_TLS_LIBS => "" ,
	GCONFIG_STATIC_START => "" ,
	GCONFIG_STATIC_END => "" ,
	RPM_ARCH => "x86" ,
	RPM_ROOT => "rpm" ,
) ;

my $cdb = new CompilationDatabase( $src_dir , ["-DG_UNIX=1"], ["-I$src_to_top"] , ["-std=c++11","-pthread"] , \%switches , \%vars ) ;
$cdb->{m_full_paths} = 1 ; # grr

if( $show_list )
{
	print join( "\n" , $cdb->list() , "" ) ;
}
else
{
	print "[\n" ;
	print join( ",\n" , $cdb->stanzas() ) ;
	print "]\n" ;
}

