#!/usr/bin/perl
use File::Copy;
use File::Path;
use File::Basename;
use POSIX qw(strftime);

%subst = ( );
@subst_files = ( "private/casafeathertool.py" );
sub subst {
    my $root = shift(@_);
    for $f ( @subst_files ) {
        my $path = "$root/$f";
        open( DST, "< $path");
        @dest = <DST>;
        close(DST);
        open( DST, "> $path");
        foreach ( @dest ) {
            foreach $k ( keys %subst ) {
                s|$k|$subst{$k}|;
                print DST $_;
            }
        }
        close( DST );
    }
}

sub rsync {
    my ($from, $to) = @_;
    my $cmd;
    if ( -f $from || (-d $from && $from =~ m|/$|) ) {
        $cmd = "rsync -aq $from $to";
    } else {
         $cmd = "rsync -aq $from/ $to";
    }
    print("\t$cmd\n");
    open( RSYNC, "$cmd 2>&1 |" );
    for ( <RSYNC> ) { print "\t>\t$_" }
    close( RSYNC );
}

sub get_proto {
    my $path = shift(@_);
    my $name = basename($path);
    my $dir = dirname($path);
    if ( ! -f $path ) { die "protobuf spec, '$name', is not a file" }
    return ( $dir, $name );
}

$prefix = "";
$app_path = "";
$build_number = "";
foreach ( @ARGV ) {
    m|^BUILD=$| && ( next );
    m|^prefix=(.*)| && ( $prefix = $1, next );
    m|^app=(.*)| && ( $app_path = $1, next );
    m|^BUILD=(\d+.\d+.\d+)$| && ( $build_number = $1, next );

    if ( m|^BUILD=| ) { die "build number must be a number" }
    die "unknown option: $_";
}

if ( ! $prefix ) { die "no prefix specified" };
if ( ! -d $prefix) { mkpath($prefix) }
if ( ! -d $prefix) { die "cannot create prefix" }
if ( ! $app_path )  { die "no prefix specified" };

$app_name = basename($app_path);

if ( $^O eq "darwin" ) {
    if ( ! -d $app_path ) { die "app directory does not exist (or is not a directory)" }
    my( $filename, $dirs, $suffix ) = fileparse( $app_path, ".app" );
    $app_exe = "__bin__/$app_name/Contents/MacOS/$filename";
    $subst{'@APP@'} = $app_exe;

    # Apple Silicon Macs use Qt5, which requires that qt.conf is present
    $cpuarch=`uname -m`;
    chomp($cpuarch);
    print ("CPU Architecture: '$cpuarch'\n");
    if ($cpuarch eq "arm64") {
        open my $fileHandle, ">>", "$app_path/Contents/Resources/qt.conf" or die "Can't open '$app_path/Contents/Resources/qt.conf'\n";
        close $fileHandle;
    }

} else {
    if ( ! -f $app_path ) { die "app image does not exist" }
    $app_exe = "__bin__/$app_name";
    $subst{'@APP@'} = $app_exe;
}

rsync("src/casafeather", $prefix);
subst($prefix);
if ( ! -d "$prefix/private" ) { mkpath("$prefix/private") }

mkpath("$prefix/__bin__");
rsync( $app_path, "$prefix/__bin__/$app_name" );
rsync("src/setup.py","$prefix/..");

chdir("$prefix/..");
if ( $build_number ) {
    exec ( './setup.py', 'bdist_wheel', "--build=$build_number" ) or die "could not build wheel: $!";
} else {
    exec ( './setup.py', 'bdist_wheel' ) or die "could not build wheel: $!";
}