#!/usr/bin/perl


# Adds a new application to busybox


use strict;
use English;

if(@ARGV == 0) {
    die "Usage: $0 package directory\n";
}

my $dir=$ARGV[0];


my $curParagraph = "";
my $curName;
my $ifLevel = 0;

sub processLine {
    if(/^\s*#\s*if/) {
	$ifLevel++;
    } elsif(/^\s*#\s*endif/) {
	$ifLevel--;
    } elsif(/^\s*(\/\/)?\s*IF_.*?APPLET.*?\(\s*(.*?)\s*,/) {
	$curName=$2;
    } elsif(/^\s*}/) {
	$curName="{";
    }
    $curParagraph .= $_;
}


# Do Makefile
my %subMakefiles;
foreach my $dir (@ARGV) {
#    if(-f "$dir/Makefile") {
	$subMakefiles{$dir}=1;
#    }
}

if(%subMakefiles) {
    my $oldName="Makefile";
    my $newName="Makefile.$$";
    open(NEW, ">", $newName) || die "Could not write $newName ($ERRNO)\n";
    my $on=0;
    my $pfx="";
    open(MAKEFILE, "<", $oldName) || die "Could not read $oldName ($ERRNO)\n";
    while(<MAKEFILE>) {
	if(/^libs-y\s+:=\s*\\$/) {
	    $on=1;
	}
	if(/^\s*$/) {
	    if($on) {
		foreach my $dir (keys %subMakefiles) {
		    print NEW "$pfx$dir/ \\\n";
		}
	    }
	    $on=0;
	}
	if($on && /^(\s*)(.*)\/ \\$/) {
	    $pfx=$1;
	    delete $subMakefiles{$2};
	}
    print NEW $_;
    }
    close(MAKEFILE);
    close(NEW);
    rename($newName,$oldName) ||
	die "Could not rename $newName to $oldName ($ERRNO)\n";
}

# Do Config.in
my %configIn;
foreach my $dir (@ARGV) {
    if(-f "$dir/Config.src") {
	$configIn{$dir}=1;
    }
}

if(%configIn) {
    my $oldName="Config.in";
    my $newName="$oldName.$$";
    open(NEW, ">", $newName) ||
	die "Could not write $newName ($ERRNO)\n";
    open(CONFIG_IN, "<", $oldName) ||
	die "Could not read $oldName ($ERRNO)\n";
    while(<CONFIG_IN>) {
	if(/^\s*source\s+(.*)\/Config.in\s*$/) {
	    delete $configIn{$1};
	}
	print NEW $_;
    }
    close(CONFIG_IN);

    foreach my $dir (keys %configIn) {
	print NEW "source $dir/Config.in\n";
    }
    close(NEW);
    rename($newName,$oldName) ||
	die "Could not rename $newName to $oldName ($ERRNO)\n";
}

my %makefileFlags;
foreach my $dir (@ARGV) {
    if(-f "$dir/Makefile.flags") {
	$makefileFlags{$dir}=1;
    }
}

if(%makefileFlags) {
    my $oldName="Makefile.flags";
    my $newName="$oldName.$$";
    open(NEW, ">", $newName) ||
	die "Could not write $newName ($ERRNO)\n";
    open(MAKEFILE, "<", $oldName) ||
	die "Could not read $oldName ($ERRNO)\n";
    while(<MAKEFILE>) {
	if(/^\s*include \$\(srctree\)\/(.*)\/Makefile.flags*$/) {
	    delete $makefileFlags{$1};
	}
	print NEW $_;
    }
    close(MAKEFILE);

    foreach my $dir (keys %makefileFlags) {
	print NEW "include \$(srctree)/$dir/Makefile.flags\n";
    }
    rename($newName,$oldName) ||
	die "Could not rename $newName to $oldName ($ERRNO)\n";
}
