#!/usr/bin/env perl

use strict;
use warnings;
use Getopt::Std;
use File::Temp;
use Archive::Extract;
use Carp;

require "sav_chkproj.pm";

my %opts = ();
my $debug = 0;
my $tempdir = "";
my $status = 0;
my @tempa;
my $globalstatus = 0;

sub usage();
sub extract_tarball($);
sub cleanup($);
sub main();


main();
exit($globalstatus);


#--------------------------------------------

sub main(){
   my $tempout;

   getopt('',\%opts);
   $debug = 1 if exists($opts{"d"});
   
   #expecting only a tarball name as argument
   if ($#ARGV != 0){
      usage();
   }
   
   my $tarball = $ARGV[0];
   my $olddir = `pwd`;
   chomp($olddir);
   
   $status = extract_tarball($tarball);
   if (!$status){
      croak("ERR: extracting tarball failed\n");
   }
   
   if (!chdir($tempdir)){
      croak("ERR: unable to chdir into $tempdir: $!\n");
   }
   @tempa = glob('*');
   
   #if only one dir and part of proj name, proj is in that dir
   if (($#tempa == 0) && ($tarball =~ /\Q$tempa[0]/)){
      if (!chdir("${tempdir}/$tempa[0]")){ 
         croak("ERR: unable to chdir into ${tempdir}/$tempa[0]: $!\n");
      }
   }
   
   print("-> checking for gnu in project tarball name\n");
   $tempout = ($tarball =~ (/gnu/i)) ? "Yes" : "No";
   printf("\n* gnu in project name:\t\t%s\n\n",$tempout);
   
   $status = lic_file();
   print("-> Searching caseless for possible license files in root dir\n");
   $tempout = $status ? "Fail" : "Pass";
   $globalstatus = 1 if ($tempout eq "Fail");
   printf("\n* Explicit license file:\t\t%s\n\n",$tempout);

   #per file actions
   my @funcs = (\&printfile);
   process_files(".",\@funcs);
   
   if (!chdir($olddir)){
      croak("ERR: unable to restore working dir, clean $tempdir manually\n");
   }

   cleanup($tempdir);
}

sub extract_tarball($){
   my $tarball = shift;
   my $ae;

   print("-> extracting tarball\n");
   $tempdir = File::Temp->tempdir("XXXXXX");
   return "" if (! -d $tempdir);
   $ae = Archive::Extract->new(archive => $tarball) || return "";
   ($ae->extract( to => $tempdir )) || return "";
   return $tempdir;
}

sub cleanup($){
   my $dir = shift;
   return if ($dir =~ /^\/$/);
   system("rm -fr $dir");
}

sub usage(){
   print("usage: $0 [-d] <tarball>\n");
   print("\t-d: debug\n");
   exit(1);
}

