#!/usr/local/bin/perl

# Converts host key and identity files from old format to new format (1.1).
# Written by Tero Kivinen <kivinen@niksula.hut.fi>

 loop:
    foreach $file (@ARGV) {
	if (!open(FILE, "<$file")) {
	    warn "$0: Cannot open file $file : $!";
	    next loop;
	}
	$header = <FILE>;
	if ($header =~ /^SSH PRIVATE KEY FILE FORMAT 1.0\n/) {
	    $header =~ s/1.0/1.1/g;
	    undef $/;
	    $rest = <FILE>;
	    $rest = substr($rest, 0, 1) . "\001\000\000\000\000" . substr($rest, 1);
	    close(FILE);
	    if (!open(FILE, ">$file.tmp")) {
		warn "$0: Cannot open file $file.tmp for writing $file not converted : $!";
		next loop;
	    }
	    print(FILE "$header$rest");
	    close(FILE);
	    chmod(0600,"$file.tmp");
	    if (!rename("$file.tmp", $file)) {
		warn "$0: Cannot rename file $file.tmp to $file, $file not converted : $!";
		next loop;
	    }
	    print "$file converted\n";
	} else {
	    if ($header =~ /^SSH PRIVATE KEY FILE FORMAT 1.1\n/) {
		print "$file already in new format\n";
	    } else {
		print "$file is not a private key file.\n"
		}
	}
    }
