#!/usr/bin/perl
#
# cpanel - cp_util/bamboo/generate-bamboo-cookie.pl
#                                                 Copyright(c) 2015 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited
#
###################################################################################
#
# Builds an HTTP cookie that can be used by Bamboo so that EA3 help scripts can
# automate more easily.
#
# ----
#
# This is a modification of the script sent to me by Todd so that we can generate
# a cookie to access vmware-manager using the web (as opposed to SSH).
#
# The cookie must be generated by a user on the EA3 dev team using their own
# credentials.
#
# When asked if we could create a specific account for this, there seemed to be
# some push-back since vmware-manager authenticates using Manage2.  In an ideal
# world, the bot user would be locked down. However, this seems to be the easiest
# path forward to accomplish this task.
#
# The cookie generated expires after 1 year by the vmware-manager application.
# Thus, if Bamboo is unable to access vmware-manager, you will need to re-run
# this script and generate a new cookie.
#
# The cookie should be saved within the "EA3 - Internal Dev Build" plan since I
# don't think it's appropriate to have it sitting around in a script or as a file
# on the machine itself.
#
###################################################################################

use strict;
use warnings;
use WWW::Mechanize ();
use HTTP::Cookies  ();
use IO::Prompt     ();
use JSON           ();

my $BUILD_PROJECT   = q{EA3};
my $BUILD_PLAN      = q{Internal Dev Build};
my $LOGIN_MAX_TRIES = 3;
my $LOGIN_URL       = q{http://vmware-manager.dev.cpanel.net/vm/login?path=/cppack};

sub generate_cookie {
    my $cookie_jar  = HTTP::Cookies->new();
    my $mech        = WWW::Mechanize->new( 'agent' => 'ea3/generate-bamboo-cookie.pl', cookie_jar => $cookie_jar, autocheck => 1 );
    my $login_tries = 0;
    my $cookie;

    while ( $login_tries < $LOGIN_MAX_TRIES ) {
        $mech->get($LOGIN_URL);

        unless ( $mech->content =~ /manage2 login is required to proceed/ims ) {
            print STDERR "ERROR: Login page appears to be broken: $LOGIN_URL";
            return undef;
        }

        # submit authentication
        $mech->form_number(1);    # First form.
        $mech->field( 'username', IO::Prompt::prompt( '-raw', 'Enter your Manage2 login: ' ) );
        $mech->field( 'password', IO::Prompt::prompt( '-raw', '-echo' => '*', 'Enter your Manage2 password: ' ) );
        $mech->submit();

        # store the cookie given to us after logging in
        $mech->cookie_jar->scan(
            sub {
                my @c = @_;
                $cookie = \@c;
            }
        );

        # we got a cookie, we're done!
        if ($cookie) {
            last;
        }
        else {
            print STDERR "ERROR: Login failure, try again\n";
            $login_tries++;
        }
    }

    if ( $login_tries >= $LOGIN_MAX_TRIES ) {
        print STDERR "ERROR: You failed to login $LOGIN_MAX_TRIES.  Quitting.";
        return undef;
    }

    return $cookie;
}

sub show_cookie {
    my $cookie = shift;
    my $i      = 1;

    print "\nUpdate Instructions:\n";

    my @instructions = (
        q{Log into Bamboo},
        qq{Select the "$BUILD_PROJECT" Build Project},
        qq{"Edit" the "$BUILD_PLAN" Plan},
        q{Select the "Variables" tab},
        q{Add/Update "BuildCookie" variable with the output of this script},
    );

    foreach my $ins (@instructions) {
        print "$i. $ins.\n";
        $i++;
    }

    print "\nCopy-and-paste the following text:\n";
    print JSON::encode_json($cookie), "\n\n";

    return 1;
}

sub main {
    my $cookie = generate_cookie();
    return ( $cookie ? show_cookie($cookie) : 0 );
}

exit( main() ? 0 : 1 );

