#!/usr/bin/env perl

use strict;
use warnings;
use Getopt::Long qw(:config no_ignore_case bundling);
use Pod::Usage;
use JSON::XS;
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 @SUPPORTED_PANELS  = qw(cpanel destiny);
my @SUPPORTED_FLAVORS = qw(cpanel destiny);
my @TASKS             = qw(instance-create instance-status instance-terminate job-restart image-create);
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             => '',
    panel               => 'cpanel',
    flavor              => 'cpanel',
    set_active          => 'true',
    verify_image        => 'false',
    ips_secondary       => '',
    metadata            => '',
    auto_delete         => '',
    dry_run             => 0,
    subnet_id           => '',
    ip_primary          => '',
    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 _image_create;
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},
    'l|panel=s'               => \$opts{panel},
    'flavor=s'                => \$opts{flavor},
    'set-active=s'            => \$opts{set_active},
    'verify-image=s'          => \$opts{verify_image},
    'u|purpose=s'             => \$opts{purpose},
    'i|ips-secondary=s'       => \$opts{ips_secondary},
    'm|metadata=s'            => \$opts{metadata},
    'a|auto-delete=s'         => \$opts{auto_delete},
    'x|dry-run'                 => \$opts{dry_run},
    's|subnet-id=s'           => \$opts{subnet_id},
    'ip-primary=s'          => \$opts{ip_primary},
    '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|image-create)$/ ) {
        warn "Invalid task \"$opts{task}\". Valid options are: (instance-create|instance-status|instance-terminate|job-restart|image-create)\n";
        _help();
    }

    if ( $opts{env} && $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} && $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 or missing env \"$opts{env}\". Valid options are: (dev|prod)\n";
        _help();
    }

    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{panel} ) {
        my $match = 0;
        for my $p (@SUPPORTED_PANELS) {
            if ( $opts{panel} eq $p ) {
                $match = 1;
                last;
            }
        }
        unless ($match) {
            warn "Invalid panel \"$opts{panel}\". Supported panels: @SUPPORTED_PANELS\n";
            exit 1;
        }
    }

    if ( $opts{flavor} ) {
        my $match = 0;
        for my $f (@SUPPORTED_FLAVORS) {
            if ( $opts{flavor} eq $f ) {
                $match = 1;
                last;
            }
        }
        unless ($match) {
            warn "Invalid flavor \"$opts{flavor}\". Supported flavors: @SUPPORTED_FLAVORS\n";
            exit 1;
        }
    }

    if ( $opts{set_active} && $opts{set_active} !~ /^(true|false)$/ ) {
        warn "Invalid value for --set-active: \"$opts{set_active}\". Valid options are: (true|false)\n";
        _help();
    }

    if ( $opts{verify_image} && $opts{verify_image} !~ /^(true|false)$/ ) {
        warn "Invalid value for --verify-image: \"$opts{verify_image}\". Valid options are: (true|false)\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 'image-create' ) {
        unless ( $opts{region} && $opts{flavor} ) {
            warn "Region and flavor are required for image-create task.\n";
            _help();
        }
        _image_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->{panel}          = $opts{panel}          if $opts{panel};
    $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};
    $instance_args->{ip_primary}     = $opts{ip_primary}     if $opts{ip_primary};

    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}     = $opts{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 $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}, $DINO_JWT, $json_payload, $DINO_URL );
    }
    else {
        my $curl_cmd = sprintf(
            q{curl -s -X POST -H 'Content-Type: application/json' -H 'Authorization: bearer %s' --data '%s' '%s'},
            $DINO_JWT, $json_payload, $DINO_URL
        );
        my $output = `$curl_cmd`;
        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");
        }
        else {
            warn "Request failed with exit code $exit_code: $output\n";
            _log_message( "command_error: $output" );
            exit 1;
        }
    }
}

sub _image_create {
    my $json       = JSON::XS->new->utf8;
    my $image_args = {
        region => $opts{region},
        flavor => $opts{flavor},
    };

    $image_args->{set_active} = ( $opts{set_active} eq 'true' ? JSON::XS::true : JSON::XS::false );
    $image_args->{verify_image} = ( $opts{verify_image} eq 'true' ? JSON::XS::true : JSON::XS::false );

    my $payload = {
        action => 'oci.create_image',
        args   => $image_args,
    };

    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}, $DINO_JWT, $json_payload, $DINO_URL );
    }
    else {
        my $curl_cmd = sprintf(
            q{curl -s -X POST -H 'Content-Type: application/json' -H 'Authorization: bearer %s' --data '%s' '%s'},
            $DINO_JWT, $json_payload, $DINO_URL
        );
        my $output = `$curl_cmd`;
        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");
        }
        else {
            warn "Request failed with exit code $exit_code: $output\n";
            _log_message( "command_error: $output" );
            exit 1;
        }
    }
}

sub _instance_status {
    my $json = JSON::XS->new->utf8;

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

    while (1) {
        my $curl_cmd = sprintf(
            q{curl -s -H 'Content-Type: application/json' -H 'Authorization: bearer %s' '%s'},
            $DINO_JWT, $job_url
        );
        my $output = `$curl_cmd`;
        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            $job_data = $json->decode( $output );
        }
        else {
            warn "Request failed with exit code $exit_code: $output\n";
            _log_message( "command_error: $output" );
            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 $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}, $DINO_JWT, $json_payload, $DINO_URL );
    }
    else {
        my $curl_cmd = sprintf(
            q{curl -s -X POST -H 'Content-Type: application/json' -H 'Authorization: bearer %s' --data '%s' '%s'},
            $DINO_JWT, $json_payload, $DINO_URL
        );
        my $output = `$curl_cmd`;
        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");
        }
        else {
            warn "Request failed with exit code $exit_code: $output\n";
            _log_message( "command_error: $output" );
            exit 1;
        }
    }
}

sub _job_restart {
    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 $curl_cmd = sprintf(
            q{curl -s -X POST -H 'Content-Type: application/json' -H 'Authorization: bearer %s' --data '{}' '%s'},
            $DINO_JWT, $job_run_url
        );
        my $output = `$curl_cmd`;
        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");
        }
        else {
            warn "Request failed with exit code $exit_code: $output\n";
            _log_message( "command_error: $output" );
            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 -l --panel --flavor --set-active --verify-image -u --purpose -i --ips-secondary -m --metadata -a --auto-delete -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 '-l' || $prev eq '--panel' ) {
        @completions = @SUPPORTED_PANELS;
    }
    elsif ( $prev eq '--flavor' ) {
        @completions = @SUPPORTED_FLAVORS;
    }
    elsif ( $prev eq '--set-active' || $prev eq '--verify-image' ) {
        @completions = @BOOLEAN_ARGS;
    }
    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|image-create).
   -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).
   -l, --panel <panel>           Optional panel for the instance (cpanel or destiny). Defaults to cpanel.
   --flavor <flavor>             Flavor for the image (cpanel or destiny).
   --set-active <true|false>     Set image as active (defaults to true).
   --verify-image <true|false>   Verify image after creation (defaults to false).
   -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"}').
   -a, --auto-delete <duration>  Optional auto-delete duration for dev instances (e.g., '1h', '30m'). Defaults to '1h'.
   -x, --dry-run                 Dry run (print curl command instead of executing it).
   -s, --subnet-id <id>          Optional subnet ID for the instance.
   --ip-primary <ip>             Optional primary IP 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
