#!/usr/bin/env perl

# Daniel Bowling <dbowling@akamai.com>
# Feb 2020
# version 0.11 - update $ver @ line 50

use strict;
use warnings;
use Net::HTTP;
use Getopt::Long qw(:config no_ignore_case);

sub get_cp {
    # make the request
    my $s = Net::HTTP->new(
        'Host'   => "@_"
        ) || die $@;
    $s->write_request(
        'HEAD'   => "/",
        'Pragma' => "akamai-x-get-cache-key"
        );

    # read the headers
    my @ckey;
    while (my $line = <$s>) {
        # find the cache key header
        if ($line =~ /X-Cache-Key:/) {
            @ckey = split(/\//, $line); # Split ckey by forward-slash
            last;                       # Break out of loop after split
        }
    }

    # return cache key or question mark if error
    if (@ckey) {
        return $ckey[3]
    } else {
        return "?"
    }
}

# Parse options
GetOptions(
    'delimiter|d=s' => \my $sep,
    'header|H'      => \my $head,
    'help|h',       # technically does nothing right now
    'version|v'     => \my $ver
    );

# Version info option
if ($ver) {
    $ver = '0.11';
    print "$ver\n";
    exit;
}

# Choose what to do given args, STDIN, or null
if (@ARGV) {
    @_ = @ARGV                           # use args or...
} elsif (! -t STDIN) {
    chomp (@_ = <STDIN>)                 # use STDIN or...
} else {
    print "Usage: $0 <HOSTNAME(S)>\n\n"; # null, print help
    die <<'OPTIONS';
Find CP code from hostnames provided as arguments or STDIN.
    -d, --delimiter=DELIM   Change delimiting character (default is TAB)
    -H, --header            Print header with output lines
    -h, --help              Print this help message
    -v, --version           Print version
OPTIONS
}

# Delimiter character
$sep = "\t" if ! $sep;

# Print header if -H|--header is specified
print "Hostname${sep}CP Code\n" if $head;

# Begin parsing hostnames
for (@_) {
    # print hostname, delimiter, CP code and newline
    print $_ . $sep . get_cp($_) . "\n";
}