#!/usr/bin/perl

use strict;
use warnings;
use Getopt::Long qw(:config no_ignore_case bundling);
use Pod::Usage;
use JSON::XS;
use LWP::UserAgent;
use File::Path qw(make_path);
use Cwd        qw(abs_path);
use FindBin;
use File::Find;
use Data::Dumper;

my @SUPPORTED_BRANDS  = qw(bluehost hostgator hostgator_br hostgator_co hostgator_mx hostgator_cl hostgator_la);
my @SUPPORTED_REGIONS = qw(us-ashburn-1 us-phoenix-1 eu-frankfurt-1 sa-saopaulo-1 eu-madrid-1);
my @CUSTOMER_PHASES   = qw(net-new migration);
my @TASKS             = qw(instance-create instance-status instance-terminate job-restart);
my @ENVIRONMENTS      = qw(dev prod);
my @BOOLEAN_ARGS      = qw(true false);

my %opts = (
    debug               => 0,
    task                => '',
    job_id              => '',
    env                 => '',
    brand               => '',
    region              => '',
    verbose             => 0,
    hostname            => '',
    customer_phase      => '',
    purpose             => '',
    ips_secondary       => '',
    metadata            => '',
    dry_run             => 0,
    subnet_id           => '',
    register_hal        => '',
    verify_hosting_site => '',
    instance_id         => '',
    complete            => 0,
    current             => '',
    prev                => '',
);

my $DINO_URL  = '';
my $DINO_JWT  = '';
my $base_file = $FindBin::Script;

sub _help;
sub _log_message;
sub _instance_create;
sub _instance_status;
sub _instance_terminate;
sub _handle_task;
sub _generate_completions;

_setup_dino_dirs();

my @original_args = @ARGV;

GetOptions(
    'd|debug'                 => \$opts{debug},
    't|task=s'                => \$opts{task},
    'j|job-id=s'              => \$opts{job_id},
    'e|env=s'                 => \$opts{env},
    'b|brand=s'               => \$opts{brand},
    'r|region=s'              => \$opts{region},
    'v|verbose'               => \$opts{verbose},
    'h|hostname=s'            => \$opts{hostname},
    'p|customer-phase=s'      => \$opts{customer_phase},
    'u|purpose=s'             => \$opts{purpose},
    'i|ips-secondary=s'       => \$opts{ips_secondary},
    'm|metadata=s'            => \$opts{metadata},
    'x|dry-run'               => \$opts{dry_run},
    's|subnet-id=s'           => \$opts{subnet_id},
    'g|register-hal=s'        => \$opts{register_hal},
    'y|verify-hosting-site=s' => \$opts{verify_hosting_site},
    'k|instance-id=s'         => \$opts{instance_id},
    'complete'                => \$opts{complete},
    'current=s'               => \$opts{current},
    'prev=s'                  => \$opts{prev},
) or _help();

if ( $opts{complete} ) {
    _generate_completions( $opts{current}, $opts{prev} );
    exit 0;
}

_handle_task();

sub _setup_dino_dirs {
    my $dino_home = "$ENV{HOME}/.dino";
    my $log_dir   = "$dino_home/logs";
    my $token_dir = "$dino_home/tokens";

    unless ( -d $log_dir && -d $token_dir ) {
        make_path( $log_dir, $token_dir, { mode => 0700 } ) or die "Failed to create ~/.dino/{logs,tokens}: $!\n";
    }
    else {
        chmod 0700, $log_dir, $token_dir or warn "Failed to chmod ~/.dino/{logs,tokens}: $!\n";
        File::Find::find(
            sub {
                if ( -f $_ ) {
                    chmod 0600, $_ or warn "Failed to chmod $_: $!\n";
                }
            },
            $log_dir,
            $token_dir
        );
    }
}

sub _log_message {
    my $message   = join ' ', @_;
    my $timestamp = `date +"%Y-%m-%d %H:%M:%S"`;
    chomp $timestamp;
    my $log_file = "$ENV{HOME}/.dino/logs/$base_file.log";
    open my $fh, '>>', $log_file or warn "Could not open log file $log_file: $!\n";
    print $fh "[$timestamp] $message\n" if $fh;
    close $fh                           if $fh;
}

sub _help {
    pod2usage(
        {
            -exitval => 1,
            -verbose => 2,
            -message =>
"Usage: $base_file -e <dev|prod> -b <brand> -r <region> -t <instance-create|instance-status|instance-terminate|job-restart> -j (required if task instance-status or job-restart) -h (optional hostname) -p (optional customer_phase) -u (optional purpose)\n",
        }
    );
}

sub _handle_task {
    if ( $opts{debug} ) {
        warn "Debug mode enabled.\n";
    }

    if ( $opts{task} !~ /^(instance-create|instance-status|instance-terminate|job-restart)$/ ) {
        warn "Invalid task \"$opts{task}\". Valid options are: (instance-create|instance-status|instance-terminate|job-restart)\n";
        _help();
    }

    if ( $opts{env} eq 'dev' ) {
        my $token_file = "$ENV{HOME}/.dino/tokens/dev_jwt";
        if ( -f $token_file ) {
            open my $fh, '<', $token_file or die "Missing token $token_file: $!\n";
            my $line = <$fh>;
            close $fh;
            if ( $line =~ /_DINO_JWT=(.*)/ ) {
                $DINO_JWT = $1;
                chomp $DINO_JWT;
            }
            else {
                die "Invalid token file format in $token_file\n";
            }
        }
        else {
            die "Missing token $token_file\n";
        }
        $DINO_URL = 'https://beta-dino.apps.provo1.endurancemb.com/jobs';
    }
    elsif ( $opts{env} eq 'prod' ) {
        my $token_file = "$ENV{HOME}/.dino/tokens/prod_jwt";
        if ( -f $token_file ) {
            open my $fh, '<', $token_file or die "Missing token $token_file: $!\n";
            my $line = <$fh>;
            close $fh;
            if ( $line =~ /_DINO_JWT=(.*)/ ) {
                $DINO_JWT = $1;
                chomp $DINO_JWT;
            }
            else {
                die "Invalid token file format in $token_file\n";
            }
        }
        else {
            die "Missing token $token_file\n";
        }
        $DINO_URL = 'https://prod-dino.apps.provo1.endurancemb.com/jobs';
        $opts{purpose} = 'userbox' unless $opts{purpose};
    }
    else {
        warn "Invalid env \"$opts{env}\". Valid options are: (dev|prod)\n";
        exit 1;
    }

    if ( $opts{brand} ) {
        my $match = 0;
        for my $b (@SUPPORTED_BRANDS) {
            if ( $opts{brand} eq $b ) {
                $match = 1;
                last;
            }
        }
        unless ($match) {
            warn "Invalid brand \"$opts{brand}\". Supported brands: @SUPPORTED_BRANDS\n";
            exit 1;
        }
    }

    if ( $opts{region} ) {
        my $match = 0;
        for my $r (@SUPPORTED_REGIONS) {
            if ( $opts{region} eq $r ) {
                $match = 1;
                last;
            }
        }
        unless ($match) {
            warn "Invalid region \"$opts{region}\". Supported regions: @SUPPORTED_REGIONS\n";
            exit 1;
        }
    }

    if ( $opts{customer_phase} && $opts{customer_phase} !~ /^(net-new|migration)$/ ) {
        warn "Invalid customer_phase \"$opts{customer_phase}\". Valid options are: (net-new|migration)\n";
        _help();
    }

    if ( $opts{register_hal} && $opts{register_hal} !~ /^(true|false)$/ ) {
        warn "Invalid value for -g/--register-hal: \"$opts{register_hal}\". Valid options are: (true|false)\n";
        _help();
    }
    if ( $opts{verify_hosting_site} && $opts{verify_hosting_site} !~ /^(true|false)$/ ) {
        warn "Invalid value for -y/--verify-hosting-site: \"$opts{verify_hosting_site}\". Valid options are: (true|false)\n";
        _help();
    }

    unless ($DINO_JWT) {
        warn "_DINO_JWT doesn't appear to be set, did you forget to export _DINO_JWT=<token> ?\n";
        exit 1;
    }

    _log_message( "command: $base_file " . join( ' ', @original_args ) );

    if ( $opts{task} eq 'instance-create' ) {
        unless ( $opts{brand} && $opts{region} ) {
            warn "Brand and region are required for instance-create task.\n";
            _help();
        }
        _instance_create();
    }
    elsif ( $opts{task} eq 'instance-terminate' ) {
        unless ( $opts{instance_id} ) {
            warn "Instance ID is required for instance-terminate task.\n";
            _help();
        }
        _instance_terminate();
    }
    elsif ( $opts{task} eq 'instance-status' ) {
        unless ( $opts{job_id} ) {
            warn "Job ID is required for instance-status task.\n";
            _help();
        }
        _instance_status();
    }
    elsif ( $opts{task} eq 'job-restart' ) {
        unless ( $opts{job_id} ) {
            warn "Job ID is required for job-restart task.\n";
            _help();
        }
        _job_restart();
    }

    print "Operation completed.\n";
}

sub _instance_create {
    my $json          = JSON::XS->new->utf8;
    my $instance_args = {
        brand              => $opts{brand},
        region             => $opts{region},
        owner              => scalar getpwuid($<),
        final_port_timeout => 3600,
    };

    $instance_args->{purpose}        = $opts{purpose}        if $opts{purpose};
    $instance_args->{hostname}       = $opts{hostname}       if $opts{hostname};
    $instance_args->{customer_phase} = $opts{customer_phase} if $opts{customer_phase};
    $instance_args->{subnet_id}      = $opts{subnet_id}      if $opts{subnet_id};

    if ( $opts{ips_secondary} ) {
        eval { $instance_args->{ips_secondary} = $json->decode( $opts{ips_secondary} ); }
          or die "Invalid JSON for --ips-secondary: $@\n";
    }
    if ( $opts{metadata} ) {
        eval { $instance_args->{metadata} = $json->decode( $opts{metadata} ); }
          or die "Invalid JSON for --metadata: $@\n";
    }

    if ( $opts{register_hal} ) {
        $instance_args->{register_hal} = ( $opts{register_hal} eq 'true' ? JSON::XS::true : JSON::XS::false );
    }
    if ( $opts{verify_hosting_site} ) {
        $instance_args->{verify_hosting_site} = ( $opts{verify_hosting_site} eq 'true' ? JSON::XS::true : JSON::XS::false );
    }

    if ( $opts{env} eq 'dev' ) {
        $instance_args->{instance_config} = 'default';
        $instance_args->{auto_delete}     = '1h';
    }
    else {
        $instance_args->{instance_config}       = 'prod';
        $instance_args->{hal_watermark_enabled} = JSON::XS::false;
    }

    my $payload = {
        action => 'oci.create_instance',
        args   => $instance_args,
    };

    my $ua = LWP::UserAgent->new;
    $ua->default_headers->header( 'Content-Type'  => 'application/json' );
    $ua->default_headers->header( 'Authorization' => "bearer $DINO_JWT" );

    my $json_payload = $json->encode($payload);

    if ( $opts{dry_run} ) {
        print sprintf( q{curl -s -H 'content-type:application/json' -H 'authorization: bearer %s' --data '%s' '%s'\n}, "bearer $DINO_JWT", $json_payload, $DINO_URL );
    }
    else {
        my $response = $ua->post( $DINO_URL, Content => $json_payload );

        if ( $response->is_success ) {
            my $output = $response->decoded_content;
            print "$output\n";
            _log_message("command_output: $output");
        }
        else {
            warn "Request failed: " . $response->status_line . "\n";
            _log_message( "command_error: " . $response->status_line );
            exit 1;
        }
    }
}

sub _instance_status {
    my $json = JSON::XS->new->utf8;
    my $ua   = LWP::UserAgent->new;
    $ua->default_headers->header( 'Content-Type'  => 'application/json' );
    $ua->default_headers->header( 'Authorization' => "bearer $DINO_JWT" );

    my $job_url = "$DINO_URL/$opts{job_id}";
    my $job_data;

    while (1) {
        my $response = $ua->get($job_url);
        if ( $response->is_success ) {
            $job_data = $json->decode( $response->decoded_content );
        }
        else {
            warn "Request failed: " . $response->status_line . "\n";
            _log_message( "command_error: " . $response->status_line );
            exit 1;
        }

        my $status = $job_data->{status};
        if ( $status eq 'errored' ) {
            print Dumper($job_data) . "\n";
            warn "Provisioning failed\n";
            exit 1;
        }
        elsif ( $status eq 'completed' ) {
            print Dumper($job_data) . "\n";
            last;
        }

        if ( $opts{verbose} ) {
            system 'clear';
            print Dumper($job_data) . "\n";
        }
        else {
            print "Current stage: " . ( $job_data->{stage} || 'N/A' ) . "\n";
        }
        sleep 5;
    }
}

sub _instance_terminate {
    my $json          = JSON::XS->new->utf8;
    my $instance_args = { instance_id => $opts{instance_id}, };

    my $payload = {
        action => 'oci.instance.terminate',
        args   => $instance_args,
    };

    my $ua = LWP::UserAgent->new;
    $ua->default_headers->header( 'Content-Type'  => 'application/json' );
    $ua->default_headers->header( 'Authorization' => "bearer $DINO_JWT" );

    my $json_payload = $json->encode($payload);

    if ( $opts{dry_run} ) {
        print sprintf( q{curl -s -H 'content-type:application/json' -H 'authorization: bearer %s' --data '%s' '%s'\n}, "bearer $DINO_JWT", $json_payload, $DINO_URL );
    }
    else {
        my $response = $ua->post( $DINO_URL, Content => $json_payload );

        if ( $response->is_success ) {
            my $output = $response->decoded_content;
            print "$output\n";
            _log_message("command_output: $output");
        }
        else {
            warn "Request failed: " . $response->status_line . "\n";
            _log_message( "command_error: " . $response->status_line );
            exit 1;
        }
    }
}

sub _job_restart {
    my $ua = LWP::UserAgent->new;
    $ua->default_headers->header( 'Content-Type'  => 'application/json' );
    $ua->default_headers->header( 'Authorization' => "bearer $DINO_JWT" );

    my $job_run_url = "$DINO_URL/$opts{job_id}/run";

    if ( $opts{dry_run} ) {
        print sprintf( q{curl -s -X POST -H 'content-type:application/json' -H 'authorization: bearer %s' --data '{}' '%s'\n}, $DINO_JWT, $job_run_url );
    }
    else {
        my $response = $ua->post( $job_run_url, Content => '{}' );

        if ( $response->is_success ) {
            my $output = $response->decoded_content;
            print "$output\n";
            _log_message("command_output: $output");
        }
        else {
            warn "Request failed: " . $response->status_line . "\n";
            _log_message( "command_error: " . $response->status_line );
            exit 1;
        }
    }
}

sub _generate_completions {
    my ( $current, $prev ) = @_;
    my @completions;

    my $all_opts =
"-e --env -b --brand -t --task -j --job-id -r --region -d --debug -v --verbose -h --hostname -p --customer-phase -u --purpose -i --ips-secondary -m --metadata -x --dry-run -s --subnet-id -g --register-hal -y --verify-hosting-site -k --instance-id";

    if ( $prev eq '-e' || $prev eq '--env' ) {
        @completions = @ENVIRONMENTS;
    }
    elsif ( $prev eq '-b' || $prev eq '--brand' ) {
        @completions = @SUPPORTED_BRANDS;
    }
    elsif ( $prev eq '-r' || $prev eq '--region' ) {
        @completions = @SUPPORTED_REGIONS;
    }
    elsif ( $prev eq '-t' || $prev eq '--task' ) {
        @completions = @TASKS;
    }
    elsif ( $prev eq '-p' || $prev eq '--customer-phase' ) {
        @completions = @CUSTOMER_PHASES;
    }
    elsif ( $prev eq '-g' || $prev eq '--register-hal' ) {
        @completions = @BOOLEAN_ARGS;
    }
    elsif ( $prev eq '-y' || $prev eq '--verify-hosting-site' ) {
        @completions = @BOOLEAN_ARGS;
    }
    else {
        @completions = split /\s+/, $all_opts;
    }

    my @filtered_completions = grep { /\Q$current\E/i } @completions;
    print join ' ', @filtered_completions;
}

__END__

=head1 NAME

oci_server_create.pl - Manage OCI instances via DINO API

=head1 SYNOPSIS

oci_server_create.pl [options]

 Options:
   -e, --env <dev|prod>          Environment (dev or prod).
   -b, --brand <brand>           Brand to operate on. Supported: @SUPPORTED_BRANDS
   -r, --region <region>         Region to operate on. Supported: @SUPPORTED_REGIONS
   -t, --task <task>             Task to run (instance-create|instance-status|instance-terminate|job-restart).
   -j, --job-id <id>             Job ID for the task to check (required for instance-status and job-restart).
   -h, --hostname <hostname>     Optional hostname for the instance.
   -p, --customer-phase <phase>  Optional customer phase (net-new or migration).
   -u, --purpose <purpose>       Optional purpose for the instance.
   -i, --ips-secondary <json>    Optional secondary IPs for the instance (e.g., '["1.2.3.4", "5.6.7.8"]').
   -m, --metadata <json>         Optional metadata for the instance (e.g., '{"org": "HOSTGATOR"}').
   -x, --dry-run                 Dry run (print curl command instead of executing it).
   -s, --subnet-id <id>          Optional subnet ID for the instance.
   -g, --register-hal <true|false> Optional flag to register with HAL.
   -y, --verify-hosting-site <true|false> Optional flag to verify hosting site.
   -k, --instance-id <id>        Instance ID (required for instance-terminate task).
   --debug                       Enable debug output.
   -v, --verbose                 Verbose output for instance-status.
   --help                        Print this help message.
   --complete                    Internal option for bash completion.
   --current <word>              Internal option for bash completion.
   --prev <word>                 Internal option for bash completion.

=head1 DESCRIPTION

This script interacts with the DINO API to manage OCI instances, including
creating, checking status, and terminating instances. It translates the
functionality of the original bash script 'oci_server_create' into Perl.

=cut
