#!/usr/bin/perl
# Consolidate a hierarchy of kconfig menu config files (Config.in) into one file
# Record list of files for make

use strict;
use warnings;

# Macro name for file list
my $deps_name = 'deps_config_cache';
# File name for file list
my $deps_file = 'include/config/cache.conf.cmd';
# Temporary file name for file list
my $deps_file_tmp = '.tmpcache.conf.cmd';

my $fh_deps;

sub expand {
  my $file = shift;
  my $parent_file = shift;
  print "# INCLUDE_BEGIN $file\n";

  open(my $fh, '<', $file) or die "Cannot open include file $file in $parent_file\n$!";
  print $fh_deps " \\\n\t$file";
  while (<$fh>) {
    if (/^\s*source\s+([^\s#]+)\s*(#.*)?$/) {
      # For each kconfig "source" statement, recursively read sub-file
      expand($1 =~ s/^"(.*)"$/$1/r, $file);
      print "# INCLUDE_CONTINUE $file\n";
    } else {
      # Print all other lines normally
      print;
    }
  }
  close($fh) or die $!;

  # Avoid kconfig "prompt redefined" warning on missing LF at EOF
  print "\n";
  print "# INCLUDE_END $file\n";
}

open ($fh_deps, '>', $deps_file_tmp) or die $!;
print $fh_deps "$deps_name := \$(filter-out config/custom.in,";
expand($_, $0) for @ARGV;
print $fh_deps " \\\n)";
print $fh_deps "\n\n\$($deps_name): ;\n";
close ($fh_deps) or die $!;
rename ($deps_file_tmp, $deps_file) or die $!;