#!/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 Text::CSV_XS;
use Data::Dumper;
use IPC::Run qw(run);

my @SUPPORTED_BRANDS  = qw(bluehost hostgator hostgator_br hostgator_co hostgator_mx hostgator_cl hostgator_la crazydomains vodien);
my @SUPPORTED_TENANTS = qw(bhhosting bhpreprodhosting lahosting lapreprodhosting dsnhosting dsnpreprodhosting);

my %BRAND_ORG_MAP = (
    'bluehost'     => 'BLUEHOST',
    'hostgator'    => 'HOSTGATOR',
    'hostgator_br' => 'LATAM',
    'hostgator_co' => 'LATAM',
    'hostgator_mx' => 'LATAM',
    'hostgator_cl' => 'LATAM',
    'hostgator_la' => 'LATAM',
    'crazydomains' => 'DREAMSCAPE',
    'vodien',      => 'DREAMSCAPE'
);
my @SUPPORTED_REGIONS = qw(
  us-ashburn-1
  us-phoenix-1
  eu-frankfurt-1
  sa-saopaulo-1
  eu-madrid-1
  ap-singapore-1
  ap-singapore-2
  sa-valparaiso-1
  sa-bogota-1
  mx-monterrey-1
  ap-mumbai-1
  ap-sydney-1
  uk-london-1
  eu-paris-1
  sa-vinhedo-1
  ca-toronto-1
);
my @CUSTOMER_PHASES   = qw(net-new migration);
my @SUPPORTED_PANELS  = qw(cpanel destiny);
my @SUPPORTED_FLAVORS = qw(cpanel destiny);
my @SUPPORTED_SHAPES  = qw(e5 e6);
my @TASKS             = qw(instance-create instance-status instance-terminate job-restart image-create instance-schedule-terminate);
my @ENVIRONMENTS      = qw(dev prod);
my @BOOLEAN_ARGS      = qw(true false);

my %opts = (
    debug                   => 0,
    task                    => '',
    job_id                  => '',
    env                     => '',
    brand                   => '',
    region                  => '',
    tenant                  => '',
    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                    => '',
    shape                   => '',
    resources_config        => '',
    volumes_config          => '',
    volumes                 => '',
    instance_config         => '',
    monitor                 => 0,
    vcn_name                => '',
    expedite                => 0,
    name_equals             => '',
    capacity_reservation_id => '',
    availability_domain     => '',
    batch                   => '',
    batch_name              => '',
    batch_job_type          => 'migration',
    concurrency             => 5,
    ip_count                => undef,
    ip_type                 => '',
);

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;
sub _instance_schedule_terminate;
sub _build_instance_args;
sub _batch_instance_create;

_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},
    'o|tenant=s'                => \$opts{tenant},
    '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},
    'shape=s'                   => \$opts{shape},
    'resources-config=s'        => \$opts{resources_config},
    'volumes-config=s'          => \$opts{volumes_config},
    'volumes=s'                 => \$opts{volumes},
    'instance-config=s'         => \$opts{instance_config},
    'monitor'                   => \$opts{monitor},
    'vcn-name=s'                => \$opts{vcn_name},
    'expedite'                  => \$opts{expedite},
    'name-equals=s'             => \$opts{name_equals},
    'capacity-reservation-id=s' => \$opts{capacity_reservation_id},
    'availability-domain=s'     => \$opts{availability_domain},
    'batch=s'                   => \$opts{batch},
    'batch-name=s'              => \$opts{batch_name},
    'batch-job-type=s'          => \$opts{batch_job_type},
    'concurrency=i'             => \$opts{concurrency},
    'ip-count=i'                => \$opts{ip_count},
    'ip-type=s'                 => \$opts{ip_type},
) or _help();

if ( $opts{monitor} && $opts{dry_run} ) {
    warn "--monitor and --dry-run are mutually exclusive.\n";
    exit 1;
}

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|image-create|instance-schedule-terminate> -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|instance-schedule-terminate)$/ ) {
        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{tenant} ) {
        my $match = 0;
        for my $t (@SUPPORTED_TENANTS) {
            if ( $opts{tenant} eq $t ) {
                $match = 1;
                last;
            }
        }
        unless ($match) {
            warn "Invalid tenant \"$opts{tenant}\". Supported tenants: @SUPPORTED_TENANTS\n";
            exit 1;
        }

        if ( $opts{tenant} eq 'dsnhosting' || $opts{tenant} eq 'dsnpreprodhosting' ) {
            if ( $opts{env} eq 'dev' ) {
                $DINO_URL = 'https://dino.beta.sydney.hosting.newfold.com/jobs';
            }
            elsif ( $opts{env} eq 'prod' ) {
                $DINO_URL = 'https://dino.sydney.hosting.newfold.com/jobs';
            }
        }

        if ( $opts{task} eq 'image-create' && $opts{region} ) {
            $opts{region} = $opts{tenant} . '/' . $opts{region};
        }
    }

    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{shape} ) {
        my $match = 0;
        for my $s (@SUPPORTED_SHAPES) {
            if ( $opts{shape} eq $s ) {
                $match = 1;
                last;
            }
        }
        unless ($match) {
            warn "Invalid shape \"$opts{shape}\". Supported shapes: @SUPPORTED_SHAPES\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();
    }

    if ( $opts{subnet_id} && $opts{vcn_name} ) {
        warn "Cannot use both --subnet-id and --vcn-name at the same time.\n";
        _help();
    }

    if ( $opts{availability_domain} ) {
        if ( $opts{task} ne 'instance-create' ) {
            warn "--availability-domain is only supported for instance-create task.\n";
            _help();
        }
        if ( $opts{availability_domain} !~ /^\d$/ ) {
            warn "Invalid value for --availability-domain: \"$opts{availability_domain}\". It must be a single digit.\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' ) {
        if ( $opts{batch} ) {
            _batch_instance_create();
        }
        else {
            if ( $opts{purpose} && $opts{purpose} eq 'migration' && !$opts{hostname} ) {
                warn "Hostname is required for instance-create task when purpose is migration.\n";
                _help();
            }
            unless ( $opts{brand} && $opts{region} ) {
                warn "Brand and region are required for instance-create task.\n";
                _help();
            }
            _instance_create();
        }
        if ( $opts{monitor} ) {
            _instance_status();
        }
    }
    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();
        if ( $opts{monitor} ) {
            _instance_status();
        }
    }
    elsif ( $opts{task} eq 'instance-terminate' ) {
        unless ( $opts{instance_id} ) {
            warn "Instance ID is required for instance-terminate task.\n";
            _help();
        }
        _instance_terminate();
        if ( $opts{monitor} ) {
            _instance_status();
        }
    }
    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();
    }
    elsif ( $opts{task} eq 'instance-schedule-terminate' ) {
        unless ( $opts{instance_id} && $opts{name_equals} ) {
            warn "instance-id and name-equals are required for instance-schedule-terminate task.\n";
            _help();
        }
        _instance_schedule_terminate();
        if ( $opts{monitor} ) {
            _instance_status();
        }
    }

    print "Operation completed.\n";
}

sub _build_instance_args {
    my ( $options, $mode ) = @_;
    my $json          = JSON::XS->new->utf8;
    my $instance_args = {
        brand  => $options->{brand},
        region => $options->{region},
    };

    if ( $mode eq 'single' ) {
        $instance_args->{owner}              = scalar getpwuid($<);
        $instance_args->{final_port_timeout} = 3600;
    }

    $instance_args->{purpose}                 = $options->{purpose}                 if $options->{purpose};
    $instance_args->{panel}                   = $options->{panel}                   if $options->{panel};
    $instance_args->{hostname}                = $options->{hostname}                if $options->{hostname};
    $instance_args->{customer_phase}          = $options->{customer_phase}          if $options->{customer_phase};
    $instance_args->{subnet_id}               = $options->{subnet_id}               if $options->{subnet_id};
    $instance_args->{ip_primary}              = $options->{ip_primary}              if $options->{ip_primary};
    $instance_args->{shape}                   = $options->{shape}                   if $options->{shape};
    $instance_args->{vcn_name}                = $options->{vcn_name}                if $options->{vcn_name};
    $instance_args->{capacity_reservation_id} = $options->{capacity_reservation_id} if $options->{capacity_reservation_id};
    $instance_args->{availability_domain}     = $options->{availability_domain}     if $options->{availability_domain};
    $instance_args->{ip_count}                = $options->{ip_count}                if defined $options->{ip_count};
    $instance_args->{ip_type}                 = $options->{ip_type}                 if $options->{ip_type};

    if ( $options->{brand} ) {
        my $org = $BRAND_ORG_MAP{ $options->{brand} };
        if ( defined $org && $org eq 'LATAM' ) {
            $instance_args->{ip_count}      = 5;
            $options->{verify_hosting_site} = 'false';
        }
    }

    if ( $options->{resources_config} ) {
        $instance_args->{resources_config} = $options->{resources_config};
    }

    if ( $options->{volumes_config} ) {
        $instance_args->{volumes_config} = $options->{volumes_config};
    }

    if ( $options->{volumes} ) {
        eval { $instance_args->{volumes} = $json->decode( $options->{volumes} ); }
          or die "Invalid JSON for --volumes: $@\n";
    }

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

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

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

    if ( $options->{instance_config} ) {
        $instance_args->{instance_config} = $options->{instance_config};
    }

    return $instance_args;
}

sub _instance_create {
    my $json          = JSON::XS->new->utf8;
    my $instance_args = _build_instance_args( \%opts, 'single' );

    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 {
        # Use IPC::Run to avoid shell/ARG_MAX issues; send JSON via stdin
        my ( $output, $stderr ) = ( '', '' );

        run [ 'curl', '-s', '-X', 'POST', '-H', 'Content-Type: application/json', '-H', "Authorization: bearer $DINO_JWT", '--data-binary', '@-', $DINO_URL ],
          '<',  \$json_payload,
          '>',  \$output,
          '2>', \$stderr;

        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");

            my $decoded_output = eval { $json->decode($output) };
            if ($@) {
                warn "Failed to decode JSON from instance-create output: $@\n";
            }
            elsif ( $decoded_output && defined $decoded_output->{id} ) {
                if ( $opts{purpose} && $opts{purpose} eq 'migration' ) {
                    my $migration_api_host;
                    if ( $opts{env} eq 'prod' ) {
                        $migration_api_host = 'migration-api.pssh.prod.us-ashburn-1.oci.eigbox.com';
                    }
                    elsif ( $opts{env} eq 'dev' ) {
                        $migration_api_host = 'migration-api.pssh.preprod.us-ashburn-1.oci.eigbox.com';
                    }

                    if ($migration_api_host) {
                        my $migration_payload = {
                            hostname => $opts{hostname},
                            stage    => 'build',
                            task     => 'dino_spawn',
                            status   => 'started',
                            job_id   => $decoded_output->{id},
                        };
                        if ( $opts{ip_primary} ) {
                            $migration_payload->{destination} = $opts{ip_primary};
                        }
                        my $json_migration_payload = $json->encode($migration_payload);
                        my $migration_api_url      = "https://$migration_api_host/api/update";
                        my $migration_curl_cmd     = sprintf( q{curl -s -X POST -H 'Content-Type: application/json' --data '%s' '%s'}, $json_migration_payload, $migration_api_url );

                        _log_message("Executing migration API call: $migration_curl_cmd");
                        my $migration_output    = `$migration_curl_cmd`;
                        my $migration_exit_code = $? >> 8;

                        if ( $migration_exit_code == 0 ) {
                            _log_message("Migration API update successful: $migration_output");
                        }
                        else {
                            _log_message("Migration API update failed with exit code $migration_exit_code: $migration_output");
                        }
                    }
                }

                if ( $opts{monitor} ) {
                    $opts{job_id}  = $decoded_output->{id};
                    $opts{verbose} = 1;
                }
            }
            elsif ( $opts{monitor} ) {
                warn "Could not find 'id' in the instance-create output. Monitoring will not proceed.\n";
            }
        }
        else {
            warn "Request failed with exit code $exit_code: $output\n";
            _log_message("command_error: $output");
            exit 1;
        }
    }
}

sub _batch_instance_create {
    my %csv_args = (
        auto_diag           => 2,
        binary              => 1,
        allow_loose_quotes  => 1,
        allow_loose_escapes => 1,
    );

    if ( $Text::CSV_XS::VERSION >= 1.34 ) {
        $csv_args{comment} = "#";
    }

    my $csv = Text::CSV_XS->new( \%csv_args );

    my $csv_file = $opts{batch};
    unless ( -f $csv_file && -r $csv_file ) {
        die "Batch file not found or not readable: $csv_file\n";
    }

    open my $fh, "<:encoding(utf8)", $csv_file or die "Could not open batch file '$csv_file': $!\n";

    my $headers = $csv->getline($fh);
    $csv->column_names(@$headers);

    my @jobs;
    while ( my $row = $csv->getline_hr($fh) ) {
        my %instance_opts = %opts;
        for my $key ( keys %$row ) {
            $instance_opts{$key} = $row->{$key} if defined $row->{$key} and $row->{$key} ne '';
        }

        my $instance_args = _build_instance_args( \%instance_opts, 'batch' );

        my $job = {
            action => 'oci.create_instance',
            args   => $instance_args,
        };
        push @jobs, $job;
    }
    close $fh;

    unless (@jobs) {
        warn "No jobs found in batch file: $csv_file\n";
        return;
    }

    my $json       = JSON::XS->new->utf8;
    my $batch_args = {
        name     => $opts{batch_name} || "batch-create-$$",
        job_type => $opts{batch_job_type},
        size     => $opts{concurrency},
        jobs     => \@jobs,
    };

    my $payload = {
        action => 'job.batch_migration',
        args   => $batch_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 {
        # Use IPC::Run to avoid shell/ARG_MAX issues; send JSON via stdin
        my ( $output, $stderr ) = ( '', '' );

        run [ 'curl', '-s', '-X', 'POST', '-H', 'Content-Type: application/json', '-H', "Authorization: bearer $DINO_JWT", '--data-binary', '@-', $DINO_URL ],
          '<',  \$json_payload,
          '>',  \$output,
          '2>', \$stderr;

        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");

            my $decoded_output = eval { $json->decode($output) };
            if ($@) {
                warn "Failed to decode JSON from batch-create output: $@\n";
            }
            elsif ( $decoded_output && defined $decoded_output->{id} ) {
                if ( $opts{monitor} ) {
                    $opts{job_id}  = $decoded_output->{id};
                    $opts{verbose} = 1;
                }
            }
            elsif ( $opts{monitor} ) {
                warn "Could not find 'id' in the batch-create output. Monitoring will not proceed.\n";
            }
        }
        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->{brand} = $opts{brand} if $opts{brand};

    $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 {
        # Use IPC::Run to avoid shell/ARG_MAX issues; send JSON via stdin
        my ( $output, $stderr ) = ( '', '' );

        run [ 'curl', '-s', '-X', 'POST', '-H', 'Content-Type: application/json', '-H', "Authorization: bearer $DINO_JWT", '--data-binary', '@-', $DINO_URL ],
          '<',  \$json_payload,
          '>',  \$output,
          '2>', \$stderr;

        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");
            if ( $opts{monitor} ) {
                my $decoded_output = $json->decode($output);
                if ( defined $decoded_output->{id} ) {
                    $opts{job_id}  = $decoded_output->{id};
                    $opts{verbose} = 1;
                }
                else {
                    warn "Could not find 'id' in the image-create output. Monitoring will not proceed.\n";
                }
            }
        }
        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 {
        # Use IPC::Run to avoid shell/ARG_MAX issues; send JSON via stdin
        my ( $output, $stderr ) = ( '', '' );

        run [ 'curl', '-s', '-X', 'POST', '-H', 'Content-Type: application/json', '-H', "Authorization: bearer $DINO_JWT", '--data-binary', '@-', $DINO_URL ],
          '<',  \$json_payload,
          '>',  \$output,
          '2>', \$stderr;

        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");
            if ( $opts{monitor} ) {
                my $decoded_output = $json->decode($output);
                if ( defined $decoded_output->{id} ) {
                    $opts{job_id}  = $decoded_output->{id};
                    $opts{verbose} = 1;
                }
                else {
                    warn "Could not find 'id' in the instance-terminate output. Monitoring will not proceed.\n";
                }
            }
        }
        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 _instance_schedule_terminate {
    my $json          = JSON::XS->new->utf8;
    my $instance_args = {
        instance_id => $opts{instance_id},
        name_equals => $opts{name_equals},
    };

    $instance_args->{region} = "$opts{tenant}/$opts{region}";

    if ( $opts{expedite} ) {
        $instance_args->{grace_period_days} = 0;
        $instance_args->{low_grace_period}  = JSON::XS::true;
    }

    my $payload = {
        action => 'oci.instance.schedule_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 {
        # Use IPC::Run to avoid shell/ARG_MAX issues; send JSON via stdin
        my ( $output, $stderr ) = ( '', '' );

        run [ 'curl', '-s', '-X', 'POST', '-H', 'Content-Type: application/json', '-H', "Authorization: bearer $DINO_JWT", '--data-binary', '@-', $DINO_URL ],
          '<',  \$json_payload,
          '>',  \$output,
          '2>', \$stderr;

        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");
            if ( $opts{monitor} ) {
                my $decoded_output = $json->decode($output);
                if ( defined $decoded_output->{id} ) {
                    $opts{job_id}  = $decoded_output->{id};
                    $opts{verbose} = 1;
                }
                else {
                    warn "Could not find 'id' in the instance-schedule-terminate output. Monitoring will not proceed.\n";
                }
            }
        }
        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 -o --tenant -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 --ip-primary -g --register-hal -y --verify-hosting-site -k --instance-id --shape --resources-config --volumes-config --volumes --instance-config --monitor --vcn-name --expedite --name-equals --capacity-reservation-id --availability-domain --batch --batch-name --batch-job-type --concurrency --ip-count --ip-type";

    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 '-o' || $prev eq '--tenant' ) {
        @completions = @SUPPORTED_TENANTS;
    }
    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 '--shape' ) {
        @completions = @SUPPORTED_SHAPES;
    }
    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;
    }

    # Arguments that take arbitrary values - no specific completions
    elsif ($prev eq '-j'
        || $prev eq '--job-id'
        || $prev eq '-h'
        || $prev eq '--hostname'
        || $prev eq '-u'
        || $prev eq '--purpose'
        || $prev eq '-i'
        || $prev eq '--ips-secondary'
        || $prev eq '-m'
        || $prev eq '--metadata'
        || $prev eq '-a'
        || $prev eq '--auto-delete'
        || $prev eq '-s'
        || $prev eq '--subnet-id'
        || $prev eq '--ip-primary'
        || $prev eq '-k'
        || $prev eq '--instance-id'
        || $prev eq '--resources-config'
        || $prev eq '--volumes-config'
        || $prev eq '--volumes'
        || $prev eq '--instance-config'
        || $prev eq '--vcn-name'
        || $prev eq '--name-equals'
        || $prev eq '--capacity-reservation-id'
        || $prev eq '--availability-domain'
        || $prev eq '--batch'
        || $prev eq '--batch-name'
        || $prev eq '--batch-job-type'
        || $prev eq '--concurrency'
        || $prev eq '--ip-count'
        || $prev eq '--ip-type' )
    {
        @completions = ();    # Empty array for arbitrary values
    }
    else {
        # If prev is empty (first argument) or current starts with '-', suggest all options
        if ( !defined $prev || $prev eq '' || $current =~ /^-/ ) {
            @completions = split /\s+/, $all_opts;
        }
        else {
            @completions = ();    # No suggestions if it's a value for an unhandled arg
        }
    }

    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
   -o, --tenant <tenant>         Tenant to build in (image-create task only). Supported: @SUPPORTED_TENANTS
   -t, --task <task>             Task to run (instance-create|instance-status|instance-terminate|job-restart|image-create|instance-schedule-terminate).
   -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. Cannot be used with --vcn-name.
   --ip-primary <ip>             Optional primary IP for the instance.
   --ip-count <int>              Optional number of IPs to attach to the instance.
   --ip-type <type>              Optional type of IP to use for the instance.
   --shape <shape>               Optional OCI shape for the instance.
   --volumes <json>              Optional volumes for the instance (e.g., '[{"name": "data", "size": 100}]').
   --vcn-name <name>             Optional VCN name to use for the instance. Cannot be used with --subnet-id.
   --capacity-reservation-id <id> Optional capacity reservation ID for the instance.
   --availability-domain <digit> Optional availability domain for the instance (single digit).
   --batch <file>              Path to a CSV file for batch instance creation.
   --batch-name <name>         Name for the batch job.
   --batch-job-type <type>     Job type for the batch job (defaults to 'migration').
   --concurrency <integer>     Concurrency for batch jobs (defaults to 5).
   -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).
   --instance-config <config>    Optional instance config to use.
   --expedite                    Optional flag to expedite instance termination (sets grace_period_days to 0 and low_grace_period to true).
   --name-equals <name>          Mandatory for instance-schedule-terminate. Specifies the name of the instance to terminate.
   --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
y of the original bash script 'oci_server_create' into Perl.

=cut
' into Perl.

=cut
h script 'oci_server_create' into Perl.

=cut
' into Perl.

=cut
