package VineLinux::VSS::Init;

use strict;
use warnings;

use FileHandle;
use Email::Valid::Loose;

our $config;

sub run {
    my $class = shift;
    $config = shift;

    if (-e $config) {
      print "Stop. $config is exist.\n";
      exit 1;
    }

    $class->set;
}

sub set {
    my $class = shift;

    my %data;
    my $stdin;

    print 'User ID?: ';
    chomp($stdin = <STDIN>);
    $data{'packager_name'} = $class->_inputdata_check($stdin,'id');
    print 'User name?: ';
    chomp($stdin = <STDIN>);
    $data{'packager_fullname'} = $class->_inputdata_check($stdin,'name');
    print 'User email address?: ';
    chomp($stdin = <STDIN>);
    $data{'packager_email'} = $class->_inputdata_check($stdin,'email');

    $class->create(\%data);
}

sub _inputdata_check {
    my $class = shift;
    my $data = shift;
    my $type = shift;

    if ($type eq 'id') {
	if ($data =~ m/^\w+$/) {
	    return $data;
	} else {
	  exit 1;
	}
    } elsif ($type eq 'name') {
	if ($data =~ m/^\s?[\w\s\,\.]+(\s|\w)$/) {
	    return $data;
	} else {
	  print "ERROR: invalid value!\n";
	  exit 1;
	}
    } elsif ($type eq 'email') {
	if (Email::Valid::Loose->address($data)) {
	  return $data;
	} else {
	  print "ERROR: invalid email address!\n";
	  exit 1;
	}
    } else {
      exit 1;
    }
}

sub create {
    my $class = shift;
    my $data = shift;

    my $fh = FileHandle->new;
    $fh->open($config,'w');
    $fh->print("packager_name: $data->{packager_name}\n");
    $fh->print("packager_fullname: $data->{packager_fullname}\n");
    $fh->print("packager_email: $data->{packager_email}\n");
    print "create: $config\n";
}

1;


