#! /usr/bin/perl

# --- GDIS install script (redirect errors -> install.log)

open(STDERR, ">install.log");

# pre-checks os / files (eg pkg-config) / libs

$osmakefile = &check_os();

# TODO - print help on where to get if not installed?
&check_program("pkg-config") || die;

print ("Checking pre-requisite packages.\n");

# TODO - print help on where to get if not installed?
&check_library("gtk+-2.0") || die;
&check_library("gtkglext-1.0") || die;

# print current options + any warnings etc
do
  {
  print "Enter Install location: ";
  $_ = <>;
  chomp;
  }
while (&check_install($_));

$dest = $_."/";

# allow editing of make/install options
# TODO - if cant open - attempt to open in current directory
&build_makefile($osmakefile);

# perform make
if (system("make -f makefile.gdis") != 0)
  {
  print "GDIS compile failed - check install.log\n";
  close(STDERR);
  exit;
  }
else
  {
  print "GDIS compile successful.\n";
  }

# perform install / strip 
# copy gdis exec + manual etc etc to install location
# dont install if dest is ./
if (length($dest) > 2)
  {
  print "Installing GDIS in: [$dest]\n";

  system("strip gdis");
  system("cp gdis $dest");
  system("cp gdis.elements $dest");
  system("cp gdis.library $dest");
  system("cp gdis.manual $dest");
  }

print "done.\n";

close(STDERR);
exit;

# --- subroutines

# --- returns the os specific makefile
sub check_os
{
$os = "makefile.linux";

open(OUT, "uname -a |");

while (<OUT>)
  {
  if (/Linux/)
    {
    $os = "makefile.linux";
    }
  if (/Darwin Kernel/)
    {
    $os = "makefile.osx";
    }
  }

close(OUT);

return $os;
}

# -- checks is directory is a valid install location
sub check_install
{
print "$_[0] : ";

stat($_[0]);

if (!-e _)
  {
  print "does not exist.\n";
  return(1);
  }
if (!-d _)
  {
  print "is not a directory.\n";
  return(1);
  }
if (!-w _)
  {
  print "is not writable by you.\n";
  return(1);
  }

print " [ok]\n";

return(0);
}

# -- checks if argument string is a valid executable
sub check_program
{
$ret = system($_[0]);

if ($ret == -1)
  {
  print "Missing program: $_[0]\n";
  return(0);
  }
return(1);
}

# -- primitive for pkg-config checking
sub check_library
{
print "$_[0] 		";
if (system("pkg-config --exists $_[0]"))
  {
  print "[not found]\n";
  return(0);
  }
else
  {
  print "[ok]\n";
  }
return(1);
}

# CURRENT - create a minimal makefile
# NB: can effect a make clean etc etc through perl script
sub build_makefile
{
open(OUT, ">makefile.gdis") || die;

print OUT "# --- auto generated GDIS makefile\n\n";

# TODO - pass OS as argument
print OUT "include $_[0]\n";
print OUT "include makefile.src\n\n";

print OUT "OBJ = \$(SRC:.c=.o)\n\n";

print OUT "gdis: \$(OBJ)\n";
print OUT "\t\$(CC) \$(OBJ) \$(LDFLAGS) -o gdis \$(LIBS)\n";

print OUT ".c.o:\n";
print OUT "\t\$(CC) \$(CFLAGS) -c \$< \$(INCS)\n";

close(OUT);
}
