##########################################################################
#初期インストール時の設定を自動化するプログラム Solaris用
#2008/11/24 hama
##########################################################################

use warnings;
use strict;
use Net::Telnet;

##########################################################################
#変数の宣言
##########################################################################

my $host = "test";
my $domain = 'mailtest.test';
my $ipaddr = '192.168.1.100';

my $hostlocal = 'localhost';
my $user = 'root';
my $pass = 'password';
my $prompt = '/[\$%#>] $/';
my $adduser = 'hama2';
my $userpass = 'password';

##変更したいファイル名:変更したい文字列:変更後の文字列を列挙

my @changefile = (
       '/etc/default/login:CONSOLE=/dev/console:#CONSOLE=/dev/console',
       "\/etc\/hosts\:$ipaddr\:$ipaddr     $host\.$domain"
       );

##作成したいファイル名:文字列を列挙

my @makefile = (
       "\/\.bashrc\:PS1\=\"\[\\u\@\\H \\W\] \"\nexport PS1",
       "\/\.inputrc\:set bell\-style none"
       );

##########################################################################
#main routine
##########################################################################

##ファイルの追加と内容の変更

foreach my $changelist(@changefile){
       &changeconf($changelist);
}

foreach my $makelist(@makefile){
       &makeconf($makelist);
}

##ユーザの追加とキーボードタイプの変更

system("useradd \-m \-d \/export\/home\/$adduser $adduser");
system('eeprom kbd-type=Japanese\(106\)');

##localhost にtelnetログインして追加ユーザのpasswordを変更する。

my $telnet = new Net::Telnet(
      Timeout => 10
);
$telnet->open($hostlocal);
$telnet->waitfor('/login:/i');
$telnet->print($user);
$telnet->waitfor('/Password:/i');
$telnet->print($pass);
$telnet->waitfor($prompt);

my $result;
$telnet->print('LANG=C');
($result) = $telnet->waitfor($prompt);
$telnet->print('export LANG');
($result) = $telnet->waitfor($prompt);
$telnet->print("passwd $adduser");
($result) = $telnet->waitfor(String => "New Password\:");
$telnet->print($userpass);
($result) = $telnet->waitfor(String => "Re\-enter new Password\:");
$telnet->print($userpass);
($result) = $telnet->waitfor($prompt);

$telnet->close;

##########################################################################
#sub routine
##########################################################################

##ファイルの内容変更サブルーチン

sub changeconf{
       my ($list) = @_;
       my @splitlist = split(/:/, $list);

       open(FILE, $splitlist[0]) or die "$!"; #置換前のファイルをopenして読込み
       my @file = <FILE>;
       close(FILE);

       foreach my $line (@file) {
               $line =~ s/$splitlist[1]/$splitlist[2]/g; #文字列を置換
       }

       open(FILE2, "> $splitlist[0]") or die "$!"; #ファイルを書込みモードでopen
       print FILE2 @file;
       close(FILE2);
}

##ファイルの新規作成サブルーチン

sub makeconf{
       my ($list) = @_;
       my @splitlist = split(/:/, $list);
       open(FILE, "> $splitlist[0]"); #ファイルを書込みモードでopen
       print FILE $splitlist[1];
       close(FILE);
}