#!/usr/bin/perl

use strict;
use Getopt::Long;


my $server;
my $initiator_name;
my $username;
my $password;
my $auth_type;
my $help_flag;
my $display_flag;

if(@ARGV == 0) {
	usage();
	exit 0;
}

GetOptions(
	"h|help" => \$help_flag,
	"d|display" => \$display_flag,
	"s|server=s" => \$server,
	"i|initiator-name=s" => \$initiator_name,
	"a|auth-type=s" => \$auth_type,
	"u|username=s" => \$username,
	"p|password=s" => \$password);
	

if($help_flag) {
	usage();
	exit 0;
}

if($display_flag) {
	display();
	exit 0;
}
open FILE, ">/etc/initiatorname.iscsi";
print FILE "InitiatorName=:$initiator_name\n";
close FILE;


if($auth_type eq "Anonymous") {
	open FILE, ">/etc/iscsi.conf";
	print FILE "DiscoveryAddress=$server\n";
	close FILE;
	exit 0;
} elsif($auth_type eq "CHAP") {
	open FILE, ">/etc/iscsi.conf";
	print FILE "DiscoveryAddress=$server\n";
	print FILE "\tUsername=$username\n";
	print FILE "\tPassword=";
	while(length $password > 0) {
		my $ch = substr($password, 0, 1);
		$password = substr($password, 1);
		if($ch eq '%') {
			my $value = substr($password, 0, 2);
			$password = substr($password, 2);
			$ch = chr hex $value;
		}
		print FILE $ch;
	}
	print FILE "\n";
	close FILE;
	exit 0;
} else {
	print STDERR "Unknown authentication type: $auth_type\n";
	exit 255;
}


sub usage
{
	print STDOUT <<END;
Usage:
	iscsiSetServer OPTIONS
	
	OPTIONS:
		-h|--help
		-d|--display
		-s|--server <server> 
		-i|--initiator-name <initiator name>
		-a|--auth-type Anonymous|CHAP
		-u|--username <username>
		-p|--passowrd <password>
		
END

	return;
}


sub display
{
	my @lines = `cat /etc/initiatorname.iscsi 2>>/dev/null`;
	chomp @lines;
	my ($line) = grep(/InitiatorName=/, @lines);
	my ($name, $value) = split(/=/, $line);
	print STDOUT "InitiatorName=$value\n";

	@lines = `cat /etc/iscsi.conf`;
	chomp @lines;

	($line) = grep(/DiscoveryAddress=/, @lines);
	($name, $value) = split(/=/, $line);
	print STDOUT "Server=$value\n";

	($line) = grep(/Username=/, @lines);
	if(length $line == 0) {
		print STDOUT "AuthType=Anonymous\n";
	} else {
		print STDOUT "AuthType=CHAP\n";
		($name, $value) = split(/=/, $line);
		print STDOUT "Username=$value\n";
		($line) = grep (/Password=/, @lines);
		($name, $value) = split(/=/, $line);
		print STDOUT "Password=$value\n";
	}

	return 0;
}

