#!perl
use strict;
use warnings;
use Config;

my $tmp  = ($ENV{TEMP} // '.')."/install-$$.bat";
my $cmd = $Config{sitebin} . "/mitdk2pop-win32.cmd";

my $what = $ARGV[0] // 'wizard';

if ($what eq 'wizard') {
	print "Starting browser..\n";
	system 'start /b http://localhost:9999/';
	print "You can close [x] this window when finished or if you want to abort the process\n\n";
	print "Starting authenticator...\n";
	system 'mitdk-authenticate --win32-install' and die "Cannot run mitdk-authenticate:$!\n";
} elsif ($what eq 'install') {
	open F, ">", $cmd or die $!;
	print F "\@start /b wperl $Config{sitebin}/mitdk2pop -p 8111\n";
	print F "\@start /b wperl $Config{sitebin}/mitdk-renew-lease -l -a -p 8112\n";
	close F;

	my $ps = <<PS;
set TARGET='$cmd'
set SHORTCUT='%userprofile%\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\mitdk2pop.lnk'
set PWS=powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile

%PWS% -Command "\$ws = New-Object -ComObject WScript.Shell; \$s = \$ws.CreateShortcut(%SHORTCUT%); \$S.TargetPath = %TARGET%; \$S.Save()"
PS

	open F, ">", $tmp or die $!;
	print F $ps;
	close F;
	system $tmp and die "Error";
	unlink $tmp;

	print "\n\nLOOKS OKAY\n";
} elsif ( $what eq 'start') {
	system $cmd;
} elsif ( $what eq 'stop') {
	require IO::Socket::INET;
	my $sock = IO::Socket::INET-> new(
		PeerAddr => '127.0.0.1',
		PeerPort => 8111,
		Proto    => 'tcp',
	);
	if ( $sock ) {
		$_=<$sock>;
		print $sock "_terminate\n";
		close $sock;
	} else {
		warn "mitdk2pop is not running\n";
	}

	$sock = IO::Socket::INET-> new(
		PeerAddr => '127.0.0.1',
		PeerPort => 8112,
		Proto    => 'tcp',
	);
	if ( $sock ) {
		print $sock "stop\n";
		close $sock;
	} else {
		warn "mitdk-renew-lease is not running\n";
	}
} elsif ( $what eq 'remove') {
	unlink "$ENV{userprofile}\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\mitdk2pop.lnk" or die "Cannot remove:$!";
	print "Removed okay\n";
} else {
	die "Nothing to do";
}
