#!/usr/bin/perl

use strict;
use warnings;

use Carp qw(confess);

use Data::Dumper;
use File::Basename;
use File::Path;
#use Sys::RunAlone;
use List::Util qw(shuffle);
#use Ernad::Learn;

use Ernad::Erimp;

my $impna = $ARGV[0] // '';
if(not $impna) {
  print "and your impna is?\n";
  exit;
}

if($impna eq 'nep') {
  print "I can't run for nep.\n";
  exit;
}

our $e=Ernad::Erimp->new({'impna'=>$impna,
                          'verbose'=>4});
my @repcodes=$e->list_repcodes();

foreach my $repcode (shuffle @repcodes) {
  my $rerc=$e->{'report'}->{$repcode};
  my $cache_dir=$rerc->{'dir'}->{'cache'};
  my $opt_dir=dirname($cache_dir);
  my $opt_learn_dir="$opt_dir/learn";
  if(not -d $opt_learn_dir) {
    mkpath($opt_learn_dir);
  }
  my $learn_dir=$e->{'dir'}->{'learn'};
  foreach my $dir (`find $learn_dir/ -name $repcode -type d`) {
    chomp $dir;
    my $part_dir=$dir;
    $part_dir=~s|$learn_dir/||;
    my $target_dir=dirname($part_dir);
    print "target_dir is $target_dir\n";
    my $out_path="../../../../learn/$part_dir";
    my $test_path="$opt_learn_dir/$out_path";
    if(not -d $test_path) {
      print "I don't see $test_path.\n";
      next;
    }
    my $sub_dir=basename($test_path);
    my $link="$opt_learn_dir/$target_dir";
    if(-l "$link") {
      print "I have a link $link\n";
      next;
    }
    my $s="cd $opt_learn_dir ; ln -s $out_path $target_dir";
    print "$s\n";
    system($s);
  }
}


__END__;
