#!/usr/bin/perl

use strict;
use warnings;
use open ':std', ':encoding(UTF-8)';

use FileHandle;

my $gitinst     = 1;
my $gitpull     = 1;
my $perlPkgInst = 1;
my $etcHosts    = 1;

## first install git
if ($gitinst) {
    system('sudo yum install -y git');

    ## install SSH key/config for github
    my $ssh_file = "$ENV{'HOME'}/.ssh/id_rsa.jgetter";
    my $ssh_conf = "$ENV{'HOME'}/.ssh/config";

    my $ssh_file_fh = FileHandle->new( $ssh_file, 'w' );
    my $ssh_conf_fh = FileHandle->new( $ssh_conf, 'w' );

    my $config = (
        q{
ForwardAgent yes
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
ServerAliveInterval 60
ServerAliveCountMax 300

Host github
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa.jgetter
}
    );
    $ssh_conf_fh->print($config);
    $ssh_conf_fh->close;

    my $rsa = (
    );
    $ssh_file_fh->print($rsa);
    $ssh_file_fh->close;

    system("sudo chown ec2-user:ec2-user $ssh_file && chmod 600 $ssh_file");
    system("sudo chown ec2-user:ec2-user $ssh_conf && chmod 644 $ssh_conf");
    system('ssh -v git@github.com');

}

if ($gitpull) {
    my $toolsDir = '/app/tools';
    system("sudo mkdir -p $toolsDir");
    system("sudo chown ec2-user:ec2-user -R $toolsDir");
    system("git clone git\@github.com:theorchard/rs-tools.git $toolsDir");
}

if ($perlPkgInst) {
    system("./yum-perl-pkgs.sh");
    system("./cpan_list.sh");

    ## perl debugger history
    my $perldb_fh = FileHandle->new( "$ENV{'HOME'}/.perldb", 'w' );
    my $perldb = ( q{&parse_options("HistFile=$ENV{HOME}/.perldb.hist"); } );
    $perldb_fh->print($perldb);
    $perldb_fh->close;

    ## perl debugger history
    my $perltidy_fh = FileHandle->new( "$ENV{'HOME'}/.perltidydc", 'w' );
    my $perltidy = (
        q{
-b            # modify in place create backup
-bext='/'     # delete *.bak if not errors
-nse          # write error messages to some-file.pl.ERR
-nst          # write to files not STDOUT
-l=140        # line width 140 chars
-bar
-ce
-sot
-sbl
-nsbl
    }
    );
    $perltidy_fh->print($perltidy);
    $perltidy_fh->close;

}

if ($etcHosts) {
    my $etcHostFile = FileHandle->new( 'hosts.db', 'w' );
    my $hosts = (
        q{
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost6 localhost6.localdomain6

## db servers
# us-west-2a
172.31.96.21    rpsdb21 dbmaster
172.31.96.22    rpsdb22 
# us-west-2b
172.31.112.23   rpsdb23
172.31.112.24   rpsdb24
# us-west-2c
172.31.128.25   rpsdb25
172.31.128.26   rpsdb26

## report server
172.31.49.17    report01


}
    );
    $etcHostFile->print($hosts);
    $etcHostFile->close;

    system("sudo mv /etc/hosts /etc/hosts.orig");
    system("sudo mv hosts.db /etc/hosts");

}
