#!/usr/bin/perl -w

use strict;

my %src;

sub src( $ ) {
    my $dir = shift;
    #print "$dir\n";
    my $dh;
    opendir $dh, $dir || return;

    while (readdir $dh) {
	next unless m/\.c$/;
	my $t = "$dir$_";
	$t =~ tr/\//\//s;
	s/\.c$/\.o/;
	$src{$_} = $t;
    }
    closedir $dh;
}

my @tgt =  split(/ /, `find .  -type d -links 2 \\(  -path './[_A-Z]*' -prune -o -print \\) | tr -s ' \t\n\r' ' '`);

my $cd;
opendir $cd, "." || die "cannot open current dir";

for my $str (@tgt) {
    #print "target: $str\n";
    chdir $cd;
    %src = ();

    # $str = e.g. "./stm32/f1"
    $str =~ s/^\.\///;
    my $lib = "$str/libarm.a";
    my @tok = split(/\//, $str);
    my $num = @tok;
    #print "$str: $num\n";

    # create source file list
    chdir $str;
    for (my $ix = $num; $ix >= 0; $ix--) {
	my $dir = "./";
	for (my $dx = 0; $dx < $ix; $dx++) {
	    $dir .= "../";
	}
	src($dir);
    }

    # create dependency list
    my $fh;
    if (!open($fh, ">depend.mk")) { warn "cannot write depend.mk"; next; }

    print $fh "libarm.a:\tlibarm.a(", join(" ", keys(%src)), ")\n";
    print $fh "\n";

    for my $k (sort keys %src) {
	my $v = $src{$k};
	#print "$str/$k:\t$v\n";
	print $fh `gcc -MM -MG -I. -I.. -I../.. $v`;
	print $fh "\t\@ echo CC \$<\n";
	print $fh "\t\@\$(CC) \$(CFLAGS) -c \$< -o \$@\n";
	print $fh "\n";
    }

    close($fh);
}

chdir $cd;
%src = ();

