#!/usr/bin/perl

use strict;
use lib '/opt/secioss/lib/perl';
use Text::CSV_XS;
use HTTP::Request::Common qw(GET POST);
use HTTP::Cookies;
use LWP::UserAgent;
use XML::Simple;
use Encode;
use Data::Dumper;

require 'LISM/Utils/lism_util.pl';

if ($#ARGV ne 1) {
    print STDERR "usage: importCSV.pl header senario\n";
    exit 1;
}

my $CONF = '/opt/secioss/etc/lism-sp.conf';
my $BASEDIR = '/opt/secioss/var/lib/csv';
my $header_file = $ARGV[0];
my $output_file = $BASEDIR.'/user.csv';
my $selenium = '/usr/local/bin/rspec';
my $senario_file = $ARGV[1];
my $header_sp = '/opt/secioss/etc/spheader.csv';

my $lismconf = XMLin($CONF, ForceArray => 1);
my $soapconf = $lismconf->{data}->{IDP}->{storage}->{SOAP};
my $url;
if ($soapconf->{proxy}[0] =~ m#^(https://[^/]+)#) {
    $url = $1.'/admin/api/';
} else {
    print STDERR "Invalid URL\n";
    exit 1;
}

my $admin;
if ($soapconf->{binddn}[0] =~ /^[^=]+=([^,]+)/) {
    $admin = $1;
} else {
    print STDERR "Invalid administrator name\n";
    exit 1;
}
my $adminpw = $soapconf->{bindpw}[0];

my $csvconf = $lismconf->{data}->{CSV}->{storage}->{CSV}->{object}{User};
my $service;
foreach my $attr (keys %{$csvconf->{attr}}) {
    if ($attr =~ /^seciossloginid;x-sys-(.+)$/) {
        $service = $1;
        last;
    }
}
if (!$service) {
    print STDERR "Invalid service id\n";
    exit 1;
}

my $header;
if (!open(HEADER, "<$header_file")) {
    print STDERR "Can't open csv header file\n";
    exit 1;
}
$header = <HEADER>;
$header =~ s/\n//;
close(HEADER);

my %keys = ('ユーザID' => 0, '社員番号' => 1, '別名' => 2, '姓' => 3, '名' => 4, '姓(かな)' => 5, '名(かな)' => 6, 'メールアドレス' => 7, 'メールエイリアス' => 8, '言語' => 10, '電話番号' => 12, 'FAX' => 13, '携帯電話番号' => 14, '自宅電話番号' => 15, '会社名' => 16, '部署' => 17, '事業所' => 18, '役職' => 19, '国' => 20, '郵便番号' => 21, '都道府県' => 22, '市区群' => 23, '町名・番地' => 24, 'ログインID' => 25, '組織' => 28);
my $pwdkey = 'パスワード';

my @elts = split(/ *, */, $header);

if (!opendir(DIR, $BASEDIR)) {
    print STDERR "Can't read $BASEDIR\n";
    exit 1;
}

my @files = readdir(DIR);
closedir(DIR);

my $ua = LWP::UserAgent->new;
my %postdata = (id => $admin, password => $adminpw, action_login => 'true');
my $req = POST $url, \%postdata;
my $res = $ua->request($req);
my $content = $res->content;
my ($sessid) = ($content =~ /<sessid>([^<]+)<\/sessid>/);
if (!$sessid) {
    print STDERR "Failed to login $url\n";
    exit 1;
}

foreach my $csv_file (@files) {
    if ($csv_file !~ /^user-[0-9]+\.csv$/) {
        next;
    }
    $csv_file = $BASEDIR.'/'.$csv_file;

    my $csvfd;
    if (!open($csvfd, "<$csv_file")) {
        print STDERR "Can't open csv file\n";
        exit 1;
    }

    if (!open(OUTPUT, ">$output_file")) {
        print STDERR "Can't open output file\n";
        exit 1;
    }

    if (-f $header_sp) {
        open(SPHEADER, "<$header_sp");
        my $spheader = <SPHEADER>;
        $spheader =~ s/\r?\n$//;
        close(SPHEADER);
        $spheader = Encode::encode('cp932',decode_utf8($spheader));
        print OUTPUT $spheader."\n";
    }

    my $csv = Text::CSV_XS->new({binary => 1, allow_whitespace => 1});
    while (my $row = $csv->getline($csvfd)) {
        my @data = @$row;
        my @output;
        for (my $i = 0; $i < @elts; $i++) {
            if ($elts[$i] eq $pwdkey) {
                my $password = randString(12, 'a..z', 'A..Z', '0..9');
                %postdata = (sessid => $sessid, action_user_setPasswd => 'true',
                id => $data[0], password => $password, service => $service);
                $req = POST $url, \%postdata;
                $res = $ua->request($req);
                my ($code) = ($content =~ /<code>([^<]+)<\/code>/);
                my ($message) = ($content =~ /<message>([^<]+)<\/message>/);
                if ($code) {
                    print STDERR "Can't set password of $data[0]: $message\n";
                    exit 1;
                }
                push(@output, $password);
            } elsif (!$elts[$i] || !defined($keys{$elts[$i]})) {
                push(@output, '');
            } else {
                push(@output, $data[$keys{$elts[$i]}]);
            }
        }
        $csv->combine(@output);
        print OUTPUT $csv->string()."\n";
    }

    print "$csv_file start Provisioning to SP...\n";
    my $output = `$selenium $senario_file 2>&1`;
    print $output."\n";

    close $csvfd;
    close OUTPUT;
    rename($csv_file, $csv_file.'.finished');
}
