#!/usr/bin/env perl
use strict;
use warnings;
use Spreadsheet::Read;
use Archive::ZIP qw(:ERROR_CODES :ZIP_METHODS);
use Path::Tiny; # For easy file existence check and absolute path
use Carp qw(croak confess); # For more robust error handling and dying gracefully
# --- Configuration ---
my $SHEET_NAME = "CMS TR";
my $ZIP_FILE_NAME = "CMS_TR_AUTOMATION.ZIP";
# --- Command Line Argument Parsing ---
unless (@ARGV == 1) {
print "Usage: $0 <path_to_xlsx_file>\n";
print "Parses the specified XLSX file, extracts steps from the '$SHEET_NAME' sheet,\n";
print "and packages them into $ZIP_FILE_NAME.\n";
exit 1;
}
my $xlsx_file = Path::Tiny->new($ARGV[0])->absolute;
unless ($xlsx_file->exists) {
croak "Error: XLSX file not found: '$xlsx_file'";
}
unless ($xlsx_file->is_file) {
croak "Error: '$xlsx_file' is not a regular file.";
}
# --- Main Logic ---
my %bash_files_content; # Stores filename => content for Bash scripts
my $in_block = 0; # Flag to indicate if we are inside a BEGIN...END block
my $current_bash_filename = ''; # Stores the filename of the current block
my @current_block_steps; # Stores [step_number, description] pairs for the current block
my $last_seen_step_number = ''; # To handle merged cells for step numbers (column A)
print "Processing file: '$xlsx_file'\n";
my $book;
eval {
$book = Spreadsheet::Read->new($xlsx_file);
};
if ($@) {
croak "Error opening XLSX file '$xlsx_file': $@";
}
unless ($book) {
croak "Error: Spreadsheet::Read failed to create a book object for '$xlsx_file'.";
}
my $sheet = $book->sheet($SHEET_NAME);
unless ($sheet) {
croak "Error: Sheet '$SHEET_NAME' not found in '$xlsx_file'.";
}
print "Reading sheet: '$SHEET_NAME'\n";
# Define column indices (Spreadsheet::Read uses 1-based indexing for columns)
# A: step number (col 1)
# B: step duration (col 2)
# C: activity (col 3)
# D: description (col 4)
my $STEP_NUM_COL = 1;
my $ACTIVITY_COL = 3;
my $DESCRIPTION_COL = 4;
# Iterate through rows. Spreadsheet::Read's row_range is 1-based.
for my $row_idx ($sheet->row_range) {
my $step_num_cell = $sheet->cell($STEP_NUM_COL, $row_idx);
my $activity_cell = $sheet->cell($ACTIVITY_COL, $row_idx);
my $description_cell = $sheet->cell($DESCRIPTION_COL, $row_idx);
# Get cell values, ensure they are defined
my $raw_step_num = $step_num_cell ? $step_num_cell->value : '';
my $activity = $activity_cell ? $activity_cell->value : '';
my $description = $description_cell ? $description_cell->value : '';
# Trim leading/trailing whitespace from values
$raw_step_num =~ s/^\s+|\s+$//g;
$activity =~ s/^\s+|\s+$//g;
$description =~ s/^\s+|\s+$//g;
# Handle merged cells for step number (Column A)
# If the current cell for step number is empty, it means it's a continuation of a merged cell
# and we should use the last encountered step number.
my $effective_step_num = '';
if ($raw_step_num ne '') {
$effective_step_num = $raw_step_num;
$last_seen_step_number = $raw_step_num; # Update last seen if a new step number exists
} else {
$effective_step_num = $last_seen_step_number;
}
# Process activity column (Column C) for BEGIN/END markers
if ($activity =~ /^BEGIN\s+(steps_\d+_to_\d+\.sh)$/) {
my $filename = $1;
if ($in_block) {
warn "Warning (Row $row_idx): Nested BEGIN or missing END before new BEGIN for '$filename'. Previous block was for '$current_bash_filename'. Saving previous block and starting new.\n";
# Force end of previous block and save its content
_finalize_current_block(\%bash_files_content, \$in_block, \$current_bash_filename, \@current_block_steps);
}
$in_block = 1;
$current_bash_filename = $filename;
@current_block_steps = (); # Clear steps for the new block
print "Info (Row $row_idx): Starting new block: '$current_bash_filename'\n";
next; # Exclude BEGIN row's description from the script content
} elsif ($activity =~ /^END\s+(steps_\d+_to_\d+\.sh)$/) {
my $filename = $1;
if (!$in_block) {
warn "Warning (Row $row_idx): END block found ('$filename') without preceding BEGIN. Ignoring this END marker.\n";
next;
}
if ($filename ne $current_bash_filename) {
warn "Warning (Row $row_idx): Mismatched END filename. Expected '$current_bash_filename', got '$filename'. Proceeding with '$current_bash_filename'.\n";
}
print "Info (Row $row_idx): Ending block: '$current_bash_filename'\n";
_finalize_current_block(\%bash_files_content, \$in_block, \$current_bash_filename, \@current_block_steps);
next; # Exclude END row's description from the script content
} elsif ($in_block) {
# This is a regular step within an active BEGIN...END block
unless ($effective_step_num ne '' || $description ne '') {
# This row has neither a step number nor a description within a block.
# It could be an empty row within a block or a row with only 'step duration'
# or 'activity' that we are not interested in for the script.
warn "Warning (Row $row_idx): Skipping row with empty step number and description in an active block.\n";
next;
}
push @current_block_steps, [$effective_step_num, $description];
} else {
# This row is not within a BEGIN...END block, so it's ignored.
# print "Debug (Row $row_idx): Skipping row (not in active block): '$activity'\n";
}
}
# After looping through all rows, check if any block was left unclosed
if ($in_block) {
warn "Warning: Unclosed BEGIN block for '$current_bash_filename' at end of file. Content will be saved.\n";
_finalize_current_block(\%bash_files_content, \$in_block, \$current_bash_filename, \@current_block_steps);
}
# --- Helper sub-routine to finalize a block and generate its Bash content ---
sub _finalize_current_block {
my ($p_bash_files_content, $p_in_block, $p_current_bash_filename, $p_current_block_steps) = @_;
my $content = '';
my $prev_step_number = ''; # To track changes in step numbers for hlb_cms_tr_step calls
foreach my $step_data (@$p_current_block_steps) {
my ($s_num, $desc) = @$step_data;
$s_num = defined $s_num ? $s_num : ''; # Ensure $s_num is not undef
# Only add hlb_cms_tr_step header if the step number actually changed
# or if it's the very first step in the block and has a number.
if ($s_num ne $prev_step_number) {
if ($s_num ne '') { # Print command only if we have a valid step number
$content .= "hlb_cms_tr_step \"[$s_num]\"\n";
} elsif ($prev_step_number eq '') {
# This case means the very first line of description for this block
# did not have a step number, which is an unusual data structure.
warn "Warning: First row description in block '$$p_current_bash_filename' has no step number.\n";
}
$prev_step_number = $s_num;
}
$content .= "$desc\n" if $desc ne ''; # Append description, ensure it's not empty
}
# Remove a single trailing newline if it's the only content from description or an artefact.
# This ensures files don't always end with an empty line unless intended.
$content =~ s/\n$// if $content =~ /\n$/ && $content !~ /\n.*\n/;
# Store the generated content under its filename
if ($$p_current_bash_filename ne '') {
# Check for duplicate filenames (e.g., if multiple BEGIN blocks refer to the same file)
if (exists $p_bash_files_content->{$$p_current_bash_filename}) {
warn "Warning: Duplicate block filename detected: '$$p_current_bash_filename'. Appending new content to existing.\n";
$p_bash_files_content->{$$p_current_bash_filename} .= "\n" . $content;
} else {
$p_bash_files_content->{$$p_current_bash_filename} = $content;
}
} else {
warn "Error: Attempted to finalize a block with an empty filename. Content lost for current block.\n";
}
# Reset block state for the next potential block
$$p_in_block = 0;
$$p_current_bash_filename = '';
@$p_current_block_steps = ();
}
# --- Zipping Generated Bash Files ---
if (!keys %bash_files_content) {
print "No Bash files were generated from the spreadsheet. No ZIP file will be created.\n";
exit 0;
}
print "Creating ZIP file: '$ZIP_FILE_NAME'\n";
my $zip = Archive::ZIP->new();
foreach my $filename (sort keys %bash_files_content) { # Sort filenames for deterministic ZIP order
my $content = $bash_files_content{$filename};
if ($content eq '') {
warn "Warning: Skipping empty script '$filename'.\n";
next;
}
my $rc = $zip->addString($content, $filename);
if ($rc != AZ_OK) {
croak "Error adding '$filename' to zip: " . $zip->error_string($rc);
}
print "Added '$filename' to ZIP archive.\n";
}
my $rc = $zip->writeToFileNamed($ZIP_FILE_NAME);
if ($rc != AZ_OK) {
croak "Error writing ZIP file '$ZIP_FILE_NAME': " . $zip->error_string($rc);
}
print "Successfully created '$ZIP_FILE_NAME' containing " . scalar(keys %bash_files_content) . " scripts.\n";
exit 0;