#!/usr/bin/perl

# take (FQDN) domain(s) as input,
# canonicalize,
# sort recursively by TLD and subdomain(s) thereof,
# output sortkey <tab> domain

$^W=1;
use strict;

$ENV{LC_ALL}='C';
my %d=();
while (<>){
	s/
		^
		\.*			# strip leading dots
		(.*?)
		\.*			# strip trailing dots
		(\r?\n)?	# strip line endings
		\z
	/\L\1/ox;		# and lowercase it
	if(!exists($d{$_})){
		# key by canonical domain,
		# value of anonymous array of reversed domain components
		$d{$_}=[reverse(split(/\./,$_))];
	};
};
for(
	sort {
		my $n=0;
		my $r=0;
		while(1){
			last if $r=$d{$a}[$n] cmp $d{$b}[$n];
			++$n;
			if($n>$#{$d{$a}}){
				if($n>$#{$d{$b}}){
					$r=0;
					last;
				}else{
					$r=-1;
					last;
				};
			}elsif($n>$#{$d{$b}}){
				$r=1;
				last;
			};
			#else continue
		};
		$r;
	} keys %d
){
	print (join('.',@{$d{$_}}),"\t",$_,'.',"\n");
};
