#!/usr/bin/perl
use strict;

use FindBin qw($Bin $Script);
$ENV{STUNNIXWS_STARTED_BY} = "${Bin}/${Script}";

my $MyBin = "$Bin/../../../";
$MyBin .= '/data/' if -d "$MyBin/data/";
$MyBin .= '/.data/' if -d "$MyBin/.data/";


my ($op) = @ARGV;
$op = 'start' if !length($op);

{
    my $binrel = "$Bin/../Resources/data/";
    if (!-r $binrel && $op eq 'start') {
	showmessage("It seems you did not 'optimize' the Prototype, most probably it will fail to start on macOS. Use CDBuilder GUI, go to 'Optimize and Pack Prototype' - 'Optimize' to fix that.");
    };
    $MyBin = $binrel if -r $binrel;
}

my @allargs;
my ($start_service,$no_splash,$force_no_compressed) = (0,0,0);

if ($ARGV[0] eq 'start_service')
{
    $ARGV[0] = 'start';
    ($start_service,$no_splash,$force_no_compressed) = (1,1,1);   

    $MyBin = "$Bin/../../../../../../";
    push @allargs,'nobrowser',1;
}

chdir $MyBin;

my $binsuffix= (index(`uname -m`,'86')>0) ? 'x86' : 'ppc';
{
    $binsuffix = 'x86' if index(`uname -m`,'arm')>0;
}

my $ossubversion = 0;
{
    my $v = (split('\.',`uname -r`))[0];
    $ossubversion = $v >= 10 ? '6' : $v >=8 ? '4' : $v >=7 ? '3' : $v>=6 ? '2' : 1;    
}

my $have_compressed = 0; #whether we have compressed cache
$have_compressed = 1 if (-r "compressed" && $binsuffix eq 'x86');
$have_compressed = 0 if $force_no_compressed;
my $ENV_PERLLIB_bk = $ENV{PERLLIB};
my $ENV_PERL5LIB_bk = $ENV{PERL5LIB};




if ($op eq 'start')
{

    if (-r "splash.bmp" && !$ENV{STUNNIXWS_NO_SPLASHSCREEN} && !$no_splash)
    {
	my $pid;
	if ( ($pid=fork()) )
	{
	    push @allargs, "_showlogo_pid",$pid;
	    $ENV{SAWS_showlogo_pid} = $pid;
	} else {
	    if ($pid==0)
	    {
		exec("$Bin/showlogo-osx-${binsuffix}",'');
		exit(0);
	    }
	};
    };        
}

if ($op) {
    push @allargs,'command',$op;
    $ENV{SAWScommand} = $op;
}
if ($op eq 'start')
{
    my $pid = $start_service ? $$ : getppid();
    push @allargs,'_osxtrayicon_pid', $pid;
    $ENV{SAWS_osxtrayicon_pid} = $pid;
}

my $perl = "perl";
my $use_64bit_perl = 0;
my $bits_suffix = '';#it can be "_x64" if httpd2 is forced

if ($binsuffix eq 'x86')
{
    if ($ossubversion >= 6) {
	#don't use system perl
	$perl = "$MyBin/perl/osx-x86/perl";    
	delete $ENV{SAWS_perl_to_run};
	if (!-r $perl) {
		$bits_suffix = '_x64';
		$use_64bit_perl = 1;
		$perl = "$MyBin/perl/osx-x86${bits_suffix}/perl";
		if (-x $perl && $have_compressed) {
		    $ENV{SAWS_perl_to_run} = "perl/osx-x86${bits_suffix}/perl";
		};
	};

    } else {
	$ENV{SAWS_perl_to_run} = "/usr/bin/perl";
    };
}


if ($have_compressed)
{
    open(F,"<compressed/projectname.dat");
    my $prjname = <F>;
    close F;


    if (length($prjname)) {
	set_perllib("$ENV{HOME}/.stunnixws-cache/$prjname");
        $ENV{SAWS_contentroot} = $MyBin;
    	
	chdir("compressed/tools/x86-macosx");
	system("./loader");
    } else {
	$have_compressed = 0;
	print STDERR "fallback case - can't use compressed runtime - empty prjname!\n";
    }
};

if (!$have_compressed) {
    delete $ENV{SAWS_contentroot};
    set_perllib($MyBin);
    my $s = system($perl,'site/stunnixwebsrv/startsite.pl', '_debug','0', @allargs);
};

if ($start_service)
{
    $SIG{TERM} = sub {
	print STDERR "got SIGTERM, stopping SAWS\n";
	$ENV{SAWScommand} = 'stop';	
	system($perl,'site/stunnixwebsrv/startsite.pl', 'command','stop');
    };
    while(1) {
	sleep(1000);
    };
}






################# utility functions follow ###################
    
sub set_perllib
{
    my($root) = @_;
    $ENV{PERLLIB} = "${root}/perl/common-inc/:${root}/perl/fallback-inc/" . 
	    (length($ENV_PERLLIB_bk)? ":${ENV_PERLLIB_bk}" : '');
    $ENV{PERL5LIB} = "${root}/perl/common-inc/:${root}/perl/fallback-inc/" . 
	    (length($ENV_PERL5LIB_bk)? ":${ENV_PERL5LIB_bk}" : '');


    if ($ossubversion >= 6)
    {
	$ENV{PERLLIB} = "${root}/perl/osx-x86${bits_suffix}/lib/:" . $ENV{PERLLIB};
	$ENV{PERL5LIB} = "${root}/perl/osx-x86${bits_suffix}/lib/:" . $ENV{PERL5LIB};
    }
}

sub showmessage{my($text)
    = @_;
    system('/usr/bin/osascript','-e',"tell application \"Finder\" to display dialog \"$text\" buttons {\"OK\"} with icon stop");
}
