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

my $tmp  = ($ENV{TEMP} // '.')."/install-$$.bat";
my $cmd = $Config{sitebin} . "/eboks2pop-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 'eboks-auth-mitid --win32-install' and die "Cannot run eboks-authenticate-mitid:$!\n";
} elsif ($what eq 'install') {
	open F, ">", $cmd or die $!;
	print F '@start /b wperl "' . $Config{sitebin} . '/eboks2pop" -p 8110' . "\n";
	close F;

	my $ps = <<PS;
set TARGET='$cmd'
set SHORTCUT='%userprofile%\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\eboks2pop.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 => 8110,
		Proto    => 'tcp',
	);
	die "Not running\n" unless $sock;
	$_=<$sock>;
	print $sock "_terminate\n";
} elsif ( $what eq 'remove') {
	unlink "$ENV{userprofile}\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\eboks2pop.lnk" or die "Cannot remove:$!";
	print "Removed okay\n";
} else {
	die "Nothing to do";
}
