#!/usr/bin/perl

#
# usage: ./install.pl
#

use Term::ANSIColor qw(:constants);

# Compile ODE if needed
print RED, "\nDPRSim: ", RESET;
print "Installing ODE...\n\n";
(-e "ode-0.5") || (system("tar xzf ode-0.5.tgz"));
system("cd ode-0.5; make configure ode-lib drawstuff-lib");

# Compile SQLite if needed
print RED, "\nDPRSim: ", RESET;
print "Building SQLite...\n\n";
(-e "sqlite") || (system("tar xzf sqlite-3.3.6.tar.gz")) || (system("mv sqlite-3.3.6 sqlite"));
if (!-d "sqlite") {
    system("cd sqlite; ./configure --disable-tcl; make");
}

# Create working directories if they do not exist

print RED, "\nDPRSim: ", RESET;
print "Creating working directories...\n";
system("mkdir --parents target; mkdir --parents target/DATA; mkdir --parents target/frame");

# Populate utils and DATA

print RED, "\nDPRSim: ", RESET;
print "Populating DATA directory...\n";
system("cp samples/*.exp target/DATA; cp samples/*.world target/DATA; cp samples/*.dpr target/DATA; cp graphics/font.ttf target/DATA; cp -r graphics/textures target/DATA; cp -r samples/obj target/DATA; rm -rf target/DATA/obj/CVS; cp -r samples/stl target/DATA; rm -rf target/DATA/stl/CVS");

# Compile and install the simulator

print RED, "\nDPRSim: ", RESET;
print "Compiling and installing Simulator...\n\n";
system("make; mv dprsim target/; mv dprsimgr target/; mv dprsimthr target/; mv dprsimthrgr target/");
#system("make; mv dprsimgr target/");

# Test for ulimit setup
print RED, "\nDPRSim: ", RESET;
print "Testing your userspace stacksize limits: ";
my $file = "$ENV{HOME}/.bashrc";
open(BASHRC, $file);
@array=<BASHRC>;
close (BASHRC);
my $found = 0;
foreach $line (@array) {
    if ( $line =~ /ulimit -s 4000000000/ ) {
	print "Stack size set properly.\n";
	$found = 1;
    }
}
if (!$found) {
    print "Setting stack size to unlimited.\n";
    system("echo 'ulimit -s 4000000000' >> $file");
    system("source $file");
}

# Print success messages

print RED, "\nDPRSim: ", RESET;
print "Installation complete.  Please run \"dprsim\" in the target/ directory.\n        Please check the README file for more detail about DPRSim.\n\n";
