#!/usr/bin/perl

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

require "gnu_chkproj.pm";

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

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

getopt('',\%opts);

$verbose = 1 if exists($opts{"v"});
$debug = 1 if exists($opts{"d"});

#expecting only a tarball name as argument
if ($#ARGV != 0){
   usage();
}

my $tarball = $ARGV[0];
my $olddir = `pwd`;

$status = extract_tarball($tarball);
croak("extracting tarball failed\n") if (!$status);

chdir($tempdir) || croak("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]/)){
   chdir("${tempdir}/$tempa[0]") || croak("unable to chdir into ${tempdir}/$tempa[0]: $!\n");
}

print("-- checking for gnu in project name tarball\n") if ($verbose);
printf("gnu in project name:\t\t%s\n",($tarball =~ (/gnu/i)) ? "Fail" : "Pass");

$status = lic_file();
print("-- Searching for file 'license' in any case in root dir\n") if ($verbose);
printf("Explicit license file:\t\t%s\n",$status ? "Fail" : "Pass");

chdir($olddir);
cleanup($tempdir);

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

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

   print("-- extracting tarball\n") if ($verbose);
   $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 [-v|-d] <tarball>\n");
   print("\t-d: debug\n");
   print("\t-v: verbose\n");
   exit(1);
}

