#!/usr/bin/perl
# Merge the cvs data and the XLSX (will not work for XLS)
use File::Slurper 'read_text','write_text';

my $template="FirstnameOnly-3.xlsx";
my $data="roomtags.csv";
my $outputdir="output";
my $temp="temp";
#---------------------------
my $work="$temp/xl/sharedStrings.xml";

MAIN: {
	#check and prep what we need..
	die("can not find $data") if (! -e "$data");
	die("can not find $template") if (! -e "$template");

	`rm $outputdir -Rf` if (-d "$outputdir");
	mkdir("$outputdir");

	open(INFO,"$data") or die ("Soemethingwong with $data");
	$headers=<INFO>;
	chomp($headers); chomp($headers);

	#Get the tab separate columnames as the first line 
	my(@headers)=split("\t",$headers);

	#for the each room (line)
	foreach(<INFO>) {
		my(%data);
		#Cleanup
		chomp($_); chomp($_);
		s/&/&amp;/g; s/</&lt;/g; s/>/&gt;/g;
		@data=split("\t",$_);
		#Map it to %data
		@data{@headers}=@data;

		#Prepare template
		`rm $temp -Rf; mkdir $temp; unzip $template -d$temp`;
		my $file=read_text("$work");
		#Replace things the need replacing
		$file =~ s/$_/$data{$_}/g foreach(sort(keys(%data)));
		#Update the tags
		write_text("$work",$file);

		#finish room
		`(cd $temp && zip -r ../$outputdir/$data{KAMR}.xlsx *)`;
	}
	close(DATA);
	#cleanup
	`rm $temp -Rf`;
}
