1#!/usr/bin/perl
2#
3
4use strict;
5
6my ($include_dir, $data_dir, $feature_file);
7
8if( @ARGV ) {
9    die "Invalid number of arguments" if scalar @ARGV != 3;
10    ($include_dir, $data_dir, $feature_file) = @ARGV;
11
12    -d $include_dir or die "No such directory: $include_dir\n";
13    -d $data_dir or die "No such directory: $data_dir\n";
14} else {
15    $include_dir = 'include/mbedtls';
16    $data_dir = 'scripts/data_files';
17    $feature_file = 'library/version_features.c';
18
19    unless( -d $include_dir && -d $data_dir ) {
20        chdir '..' or die;
21        -d $include_dir && -d $data_dir
22            or die "Without arguments, must be run from root or scripts\n"
23    }
24}
25
26my $feature_format_file = $data_dir.'/version_features.fmt';
27
28my @sections = ( "System support", "mbed TLS modules",
29                 "mbed TLS feature support" );
30
31my $line_separator = $/;
32undef $/;
33
34open(FORMAT_FILE, "$feature_format_file") or die "Opening feature format file '$feature_format_file': $!";
35my $feature_format = <FORMAT_FILE>;
36close(FORMAT_FILE);
37
38$/ = $line_separator;
39
40open(CONFIG_H, "$include_dir/config.h") || die("Failure when opening config.h: $!");
41
42my $feature_defines = "";
43my $in_section = 0;
44
45while (my $line = <CONFIG_H>)
46{
47    next if ($in_section && $line !~ /#define/ && $line !~ /SECTION/);
48    next if (!$in_section && $line !~ /SECTION/);
49
50    if ($in_section) {
51        if ($line =~ /SECTION/) {
52            $in_section = 0;
53            next;
54        }
55
56        my ($define) = $line =~ /#define (\w+)/;
57        $feature_defines .= "#if defined(${define})\n";
58        $feature_defines .= "    \"${define}\",\n";
59        $feature_defines .= "#endif /* ${define} */\n";
60    }
61
62    if (!$in_section) {
63        my ($section_name) = $line =~ /SECTION: ([\w ]+)/;
64        my $found_section = grep $_ eq $section_name, @sections;
65
66        $in_section = 1 if ($found_section);
67    }
68};
69
70$feature_format =~ s/FEATURE_DEFINES\n/$feature_defines/g;
71
72open(ERROR_FILE, ">$feature_file") or die "Opening destination file '$feature_file': $!";
73print ERROR_FILE $feature_format;
74close(ERROR_FILE);
75