#!/usr//bin/env perl

#
#  convert .tiddler into .tid files
#  useful for ginsu a TiddlyWiki, then HTTP PUT them to TiddlyWeb/TiddlySpaces
#

use strict;

sub read_file {
	my ($filename) = @_;
	undef $/;
	local *FILE;
	open FILE, "< $filename";
	binmode(FILE, ":utf8");
	my $c = <FILE>;
	close FILE;
	return $c;
}

foreach my $file (@ARGV) {

	my $tid = $file;
	my $text = "";

	if ($file =~ /.tiddler$/) {

		$tid =~ s/dler$//;
		$text = read_file($file, encoding => 'utf8');

		my $attrs = $text;
		$attrs =~ s/\s*<div([^>]*)>.*$/$1/s;
		$attrs =~ s/\s*(\w+)\s*=\s*["']([^"']*)["']\s*/$1: $2\n/gs;

		$text =~ s/^\s*<div[^>]*>\s*<\s*pre>\s*(.*)\s*<\/pre\s*>\s*<\/div\s*>\s*$/$1/s;

		$text = $attrs . "\n" . $text;

	} elsif ($file =~ /.js$/) {

		$tid =~ s/.js$/.tid/;
		$text = read_file($file . ".meta") . "\n" .  read_file($file);

	}

	if ($text) {
		print "$tid\n";
		open(FILE, "> $tid");
		binmode(FILE, ":utf8");
		print FILE $text;
		close(FILE);
	}
}