#!/usr/bin/perl -w

# lab 13 solution

#----------------------------------------------------------------------
use Net::Ping;
use Net::FTP;
use Net::SMTP;

$hostfile = "/mnt/homes/CLASSES/CIS2279/LAB13/hosts.txt";

$p = Net::Ping->new();

open(HF, "<$hostfile") || die "cannot open file: $!";
while($host = <HF>) {
    chomp($host);
    $rc = $p->ping($host);
    if($rc) {
        print "host $host is up.\n";
    }else{
        print "host $host is off-line\n";
    }
}
close(HF);

#2. Retrieve the file "/slackware/slackware64-14.2/RELEASE_NOTES" via ftp 
#   from the host mirror.csclub.uwaterloo.ca.
# set FTP variables
$host = 'mirror.csclub.uwaterloo.ca';
$ftp_user = 'anonymous';
$ftp_pass = 'mark.tucker@lyndonstate.edu';
$remote_path = '/slackware/slackware64-14.2';

print "Retrieveing file via FTP...\n";
# create new ftp object.
$ftp = Net::FTP->new($host, -Passive=>'true');

# login anonymously
$ftp->login($ftp_user,$ftp_pass) or die "Cannot login: ", $ftp->message;

$ftp->cwd($remote_path) or die "Cannot change directory: ", $ftp->message;

chdir($ENV{'HOME'}); # change to my home directory before retrieving file
$ftp->get("RELEASE_NOTES") or die "Cannot get file: ", $ftp->message;

$ftp->quit;


#3. Email the first 8 lines of the RELEASE_NOTES file you just downloaded to 
#   yourself. Use lsc-smtp.lsc.vsc.edu as the SMTP host.


# Get the first 8 lines of the file.
$file = $ENV{'HOME'}.'/RELEASE_NOTES'; # release notes file with path

open(RN, "<$file") || die "cannot read file: $!";
$counter = 0;
while($line = <RN>) {
    push(@eight, $line);
    $counter++;
    last if($counter >= 7);
}
close(RN);

print "Now sending an email...\n";
# set mail variables.
$from = 'student@metlab99.lsc.vsc.edu';
$mailhost = 'lsc-smtp.lsc.vsc.edu';
$address = 'mark.tuckerm@lsc.vsc.edu';
$subject = 'Eight lines of the Release Notes';

# create new SMTP object
$smtp = Net::SMTP->new($mailhost, Timeout=>30);

# set from address
$smtp->mail($from);

# set the recipient address
$smtp->to($address);

# start sending data
$smtp->data();

# send message data
$smtp->datasend("Subject: $subject\n\n");  # Note the two newlines
foreach $k (@eight) {
    $smtp->datasend("$k\n");
}

# terminate the message
$smtp->dataend();

# quit the smtp connection
$smtp->quit;

exit;