#!/usr/bin/perl

=head1 NAME

/usr/lib/obs/service/cpanspec - Generate a spec file for a CPAN module

=head1 SYNOPSIS

/usr/lib/obs/service/cpanspec [options]

Options:

   old              Be more compatible with old RHL/FC releases (default: disable)
   license          Include generated license texts if absent in source (default: enable)
   noprefix         Don't add perl- prefix to package name (default: disable)
   force            Force overwriting existing spec (default: enable)
   packager         Name and email address of packager (for changelog) (default: rpm)
   release          Release of package (default: 0)
   epoch            Epoch of package (default: 0)
   disttag          Disttag (default: %{?dist})
   srpm             Build a source rpm (default: disable)
   build            Build source and binary rpms (default: disable)
   cpan             CPAN mirror URL
   verbose          Be more verbose (default: enable)
   prefer-macros    Prefer macros over environment variables in the spec (default: disable)
   follow             Process build dependencies (default: disable)
   filter-requires    Specify Requires to remove
   filter-provides    Specify Provides to remove
   add-requires       Add Requires for this item
   add-provides       Add Provides for this item
   add-buildrequires  Add BuildRequires for this item
   old-file=s         Old archive file for extraction of changelog difference
   skip-changes       Do not create or update .changes file (default: enable)
   source             Glob of source, or cpan module name (default: *.tar.gz)
   outdir             Output directory
   count              How much sources i need to parse (default: 1)
   noop               Do nothing (default: disable)

=cut


use Cwd;
use File::HomeDir;
use File::Path qw(make_path);
use File::Copy;
use LWP::Simple;

use strict;
use warnings;

our $key;
our $value;
our $type;
our $source;
our $outdir;
our $count;
our $noop;

defined ($count) || ($count = 1);

my %options = (qw(
--old                     b+f
--license                 b+f
--noprefix                b+f
--force                   b+t
--srpm                    b+f
--build                   b+f
--verbose                 b+t
--prefer-macros           b+f
--follow                  b+f
--skip-changes            b+t
--packager                s-
--release                 s-
--epoch                   s-
--disttag                 s-
--cpan                    s-
--old-file                s-
),
'--filter-requires'      ,[],
'--filter-provides'      ,[],
'--add-requires'         ,[],
'--add-provides'         ,[],
'--add-buildrequires'    ,[],
'--outdir'        , \$outdir,
'--count'          , \$count,
'--noop'           ,  \$noop,
'--source'               ,[],
);

while (@ARGV){
  $key = shift @ARGV;
  $value = shift @ARGV;
  $type = $options{$key};
  if (defined ($type)){
    my $rf = ref($type);
    if ($rf eq 'ARRAY'){
      push @$type, $value;
    } elsif ($rf eq 'SCALAR'){
      $$type = $value;
    } elsif ($type eq 'b+f'){
      if ($value eq 'enable'){
        $options{$key} = 'b+t';
      }
    } elsif ($type eq 'b+t'){
      if (! $value eq 'disable'){
        $options{$key} = 'b+f';
      }
    } elsif ($type =~ /^s/ ){
      $options{$key} = "s+$value";
    } elsif ($type eq '-'){
    }
  }
}

if ((defined($noop)) && ($noop eq 'enable')){
} else {

my $sources = delete($options{'--source'}) || [];
if (! scalar(@$sources)){ 
  push @$sources, '*.tar.gz';
};

for my $source (@$sources){
  my @files = glob($source);
  if (scalar(@files) > 0 && -e $files[0]){
    push @ARGV, (map { Cwd::abs_path($_) } @files);
  } else {
    push @ARGV, $source;
  }
}

if ($count > 0 && scalar @ARGV > $count){
  @ARGV = @ARGV[0..$count-1];
}

while (($key, $type) = each(%options)){
  if (ref($type) eq 'ARRAY'){
    for (@$type){
      push @ARGV, $key, $_;
    }
  } elsif ($type eq 'b+t'){
    push @ARGV, $key;
  } elsif ($type =~ /^s\+/ ){
    push @ARGV, $key, substr($type, 2);
  }
}


if (defined($outdir)) {
  $outdir = Cwd::abs_path($outdir);
  my $yaml_src = "cpanspec.yml";
  my $yaml_target = "$outdir/cpanspec.yml";
  copy($yaml_src, $yaml_target) if -e $yaml_src && !-e $yaml_target;
  chdir $outdir;
} else {
  $outdir = Cwd::abs_path(".");
}

# Get the home directory of the current user
my $home_dir = File::HomeDir->my_home;

# Define the target directory and file name
my $target_dir = "$home_dir/.local/share/.cpan/sources/modules";
my $file_name = "02packages.details.txt.gz";
my $file_path = "$target_dir/$file_name";

# Check if the file exists
if (-e $file_path) {
    print "File '$file_path' already exists.\n";
} else {
    # Create the target directory and any necessary parent directories
    make_path($target_dir) unless -d $target_dir;

    # Download the file
    my $url = "http://www.cpan.org/modules/$file_name";
    my $result = getstore($url, $file_path);

    if (is_success($result)) {
        print "File '$file_name' downloaded successfully to '$target_dir'.\n";
    } else {
        warn "Failed to download '$file_name': " . status_message($result) . "\n";
        open(my $fh, '>', $file_path) or die "Could not open file '$file_path' $!";
        close($fh);
    }
}

  symlink(".local/share/.cpan", "$home_dir/.cpan");

  use Data::Dumper;
  print("\nCommand Line Arguments: ");
  print( Dumper(['cpanspec', @ARGV]) );
  print("\nOutput Directory: $outdir\n");
  print("CPANSPEC Exit Code: ", system('cpanspec', @ARGV), "\n");
}
