#!/usr/bin/perl

#########################################################

my ($dir_extra)="/lives/plugins/effects/";
my ($builder)="build-lives-rfx-plugin";
my ($type)="builtin"; # default

#########################################################

my ($dir);
my ($builder_location);

if (defined $ARGV[0]) {
    $type=$ARGV[0];
}

if (defined $ARGV[1]) {
    $dir=$ARGV[1];
}

#get <tempdir>
`smogrify get_tempdir rfx_builder`;
open IN,"< /tmp/.smogrify.rfx_builder";
read IN,$tmpdir,512;
close IN;
unlink "/tmp/.smogrify.rfx_builder";

if ($tmpdir eq "") {
    # TODO - run smogrify report HOME and try again
    print "You must run lives-exe and then check the value of <prefix_dir> in ~/.lives\n before you can use this routine.\n";
    exit 2;
}


# check we have the plugin builder
`smogrify get_location $builder rfx builder`;
open IN,"< $tmpdir/.smogval.rfx.builder";
read IN,$builder_location,512;
close IN;
unlink "$tmpdir/.smogval.rfx.builder";

if ($builder_location eq "") {
    print "Unable to locate $builder. Exiting.\n";
    exit 3;
}

    
if (!defined($dir)) {
    if ($type eq "builtin") {
# get the prefix_dir from ~/.lives
	`smogrify get_pref prefix_dir rfx builder`;
	open IN,"< $tmpdir/.smogval.rfx.builder";
	read IN,$dir,512;
	close IN;
	unlink "$tmpdir/.smogval.rfx.builder";
	chomp($dir);
	$dir.="/share";
    }
    else {
	`smogrify get_homedir rfx_builder`;
	open IN,"< /tmp/.smogrify.rfx_builder";
	read IN,$dir,512;
	close IN;
	unlink "/tmp/.smogrify.rfx_builder";
	chomp($dir);
    }
    $dir.=$dir_extra;
}



if ($type eq "builtin") {
    $indir=$dir."RFXscripts/";
    unlink <$indir/*~>;
    $outdir=$dir."rendered/";
}
elsif ($type eq "custom") {
    $indir=$dir."RFXscripts/custom/";
    unlink <$indir/*~>;
    $outdir=$dir."rendered/custom/";
}
elsif ($type eq "test") {
    $indir=$dir."RFXscripts/test/";
    unlink <$indir/*~>;
    $outdir=$dir."rendered/test/";
}
else {
    print "error: unknown RFX type\n";
    exit 1;
}

print "Deleting scripted plugins from $outdir\n";
&remove_scripted_plugins($outdir);

print "Building all in $indir\n";

`mkdirhier $outdir`;

opendir DIR,$indir;
while ($plugin=readdir(DIR)) {
    unless ($plugin =~ /^\./) {
	print "building $indir$plugin \n";
	system("build-lives-rfx-plugin $indir$plugin $outdir");
    }
}
close DIR;

exit 0;

######################################################################

sub remove_scripted_plugins {
    # remove only plugins with properties&0x8000
    my ($outdir)=@_;
    my ($file);
    opendir DIR,$outdir;
    while ($file=readdir(DIR)) {
	unless ($file =~ /^\./) {
	    if (-x "$outdir$file") {
		my ($fx_caps)=`$outdir$file get_capabilities`;
		if ($fx_caps&0x8000) {
		    unlink "$outdir$file";
		}
	    }
	}
    }
    closedir DIR;
}
