#!/usr/bin/perl

$target=shift @ARGV;

if($target eq 'installsrc') {
    sys_print("mkdir $ENV{SRCROOT}") unless -e $ENV{SRCROOT};
    sys_print("ditto . $ENV{SRCROOT}");
    chdir($ENV{SRCROOT});
    foreach $module (glob('*')) {
        next if $module =~ /build/;
        next if $module =~ /Make/;
        next if $module =~ /uvn/;
        next if $module =~ /\./;
        print "installing source for $module\n";
        chdir($module);
        foreach $file (glob('*.tar.bz2')) {
            sys_print("tar -xjf ".$file);
        }
        foreach $file (glob('*.tar.gz')) {
            sys_print("tar -xzf ".$file);
        }
        foreach $file (glob('patches/*')) {
            sys_print("patch -p0 < ".$file);
        }
        chdir('..');
    }

    exit();
}

if($target eq 'clean') {
    print "Cleaning out directory $ENV{SRCROOT}\n";
    chdir($ENV{SRCROOT});
    sys_print("find . -name .svn | xargs rm -rf");
    sys_print("find . -name .uvn | xargs rm -rf");
    sys_print("find . -name \"*.gz\" | xargs rm");
    sys_print("find . -name \"*.bz2\" | xargs rm");
    sys_print("find . -name patches | xargs rm -rf");
    sys_print("find . -name Sparkle.framework | xargs rm -rf");

    exit();
}

if($target eq 'install') {
    print "Install phase: \n";
    $prefix="/usr/X11";
    sys_print("mkdir $ENV{DSTROOT}") unless -e $ENV{DSTROOT};
    sys_print("mkdir $ENV{OBJROOT}") unless -e $ENV{OBJROOT};

# Must create local aclocal dir or aclocal fails
    $ACLOCAL_LOCALDIR="$ENV{DSTROOT}$prefix/share/aclocal";
    system "mkdir -p $ACLOCAL_LOCALDIR";
        
# The following is required to make aclocal find our .m4 macros
    $ENV{ACLOCAL}="aclocal -I $ACLOCAL_LOCALDIR -I $prefix/share/aclocal";
    $ENV{LIBTOOLIZE}="/usr/bin/glibtoolize";
        
# The following is required to make pkg-config find our .pc metadata files
    $ENV{PKG_CONFIG_PATH}="$ENV{DSTROOT}$prefix/lib/pkgconfig:$prefix/lib/pkgconfig:/usr/lib/pkgconfig:$ENV{PKG_CONFIG_PATH}";
    
# Set the library path so that locally built libs will be found by apps
    $ENV{LD_LIBRARY_PATH}="$prefix/lib:$ENV{LD_LIBRARY_PATH}";
    
    $ENV{PATH}="$prefix/bin:$ENV{PATH}";
    
    # Set the default font path for xserver/xorg unless it's already set
    $ENV{FONTPATH}="/usr/X11/lib/X11/fonts/misc/,/usr/X11/lib/X11/fonts/TTF/,/usr/X11/lib/X11/fonts/OTF,/usr/X11/lib/X11/fonts/Type1/,/usr/X11/lib/X11/fonts/75dpi/:unscaled,/usr/X11/lib/X11/fonts/100dpi/:unscaled,/usr/X11/lib/X11/fonts/75dpi/,/usr/X11/lib/X11/fonts/100dpi/,/Library/Fonts,/System/Library/Fonts";
    
    foreach $arch (split(/ /,$ENV{RC_ARCHS})) {
        $arch_flags_lib .= "-arch $arch ";
        if($ENV{MACOSFORGE_RELEASE} eq "YES") {
	    $arch_flags_exec .= " -arch $arch " unless $arch =~ /64/;
        } else {
            $arch_flags_exec .= " -arch $arch " unless $arch =~ /ppc/;
        }
    }
    
    $ENV{CFLAGS}="-I$ENV{DSTROOT}$prefix/include -I$prefix/include -DNO_ALLOCA -D__DEBUG__ -D_FORTIFY_SOURCE=2 -Wall -Wformat-security -ggdb3 -pipe -Os $arch_flags_lib";
    $ENV{OBJCFLAGS}="$ENV{CFLAGS}";
    $ENV{LDFLAGS}="-L$ENV{DSTROOT}$prefix/lib -L$prefix/lib -pipe $arch_flags_lib";
    
    $ENV{RC_Project_Source_Version}=0 unless exists $ENV{RC_Project_Source_Version};
    sys_print("ditto $ENV{SRCROOT}/ $ENV{OBJROOT}");

    print "Building MesaGL\n";

    chdir("$ENV{OBJROOT}/mesa/Mesa-7.2");
    sys_print("make darwin -j".`sysctl -n hw.activecpu`);
    lipoexec("progs/xdemos/glxgears");
    lipoexec("progs/xdemos/glxinfo");

    sys_print("make install DESTDIR=$ENV{DSTROOT}");

    sys_print("mkdir -p $ENV{DSTROOT}$prefix/lib/internal");
    sys_print("mv $ENV{DSTROOT}$prefix/lib/libGL.1.2.dylib $ENV{DSTROOT}$prefix/lib/internal/libMesaGL.1.dylib");
    sys_print("install_name_tool -change $prefix/lib/libGL.1.dylib $prefix/lib/internal/libMesaGL.1.dylib $ENV{DSTROOT}$prefix/lib/libOSMesa.7.dylib");

    sys_print("mkdir -p $ENV{DSTROOT}$prefix/bin");
    sys_print("cp progs/xdemos/glxgears $ENV{DSTROOT}$prefix/bin");
    sys_print("cp progs/xdemos/glxinfo $ENV{DSTROOT}$prefix/bin");
    sys_print("chown -R root:wheel $ENV{DSTROOT}$prefix/bin");

    # This is needed for the 1.5 server to build with GLX support
    sys_print("mkdir -p $ENV{DSTROOT}$prefix/include/GL/internal");
    sys_print("cp include/GL/internal/dri_interface.h $ENV{DSTROOT}$prefix/include/GL/internal");
    sys_print("chown -R root:wheel $ENV{DSTROOT}$prefix/include/GL/internal");
    sys_print("chmod 644 $ENV{DSTROOT}$prefix/include/GL/internal/*.h");

    chdir("$ENV{OBJROOT}/libGL/AppleSGLX-57");
    sys_print("make builds/libGL.1.2.dylib -j".`sysctl -n hw.activecpu`);
    sys_print("make install DESTDIR=$ENV{DSTROOT}");

    $ENV{CPPFLAGS}="-I$ENV{OBJROOT}/mesa/Mesa-7.0.4/include -I$ENV{DSTROOT}$prefix/include -I$prefix/include -DNO_ALLOCA -D__DEBUG__ -D_FORTIFY_SOURCE=2";
    $ENV{CFLAGS}="-Wall -Wformat-security -ggdb3 -pipe -Os $arch_flags_exec";
    $ENV{OBJCFLAGS}="$ENV{CFLAGS}";
    $ENV{LDFLAGS}="-L$ENV{DSTROOT}$prefix/lib -L$prefix/lib -pipe $arch_flags_exec";

    chdir("$ENV{OBJROOT}/Xquartz/xorg-server-1.4.2-apple45");
    print "Building Xquartz\n";

    sys_print("autoreconf -fvi");

    $conf_flags="--with-mesa-source=$ENV{OBJROOT}/mesa/Mesa-7.0.4 --disable-dependency-tracking --disable-nls --with-fontdir=$prefix/lib/X11/fonts --with-default-font-path='$ENV{FONTPATH}' --prefix=$prefix ";
    sys_print( "./configure $conf_flags");
    print "building\n";
    sys_print("make -j".`sysctl -n hw.activecpu`);
    sys_print("make install DESTDIR=$ENV{DSTROOT}");

    if($ENV{MACOSFORGE_RELEASE} ne "YES") {
        chdir("$ENV{DSTROOT}/Applications/Utilities/X11.app/Contents/Resources");
        foreach $locale_dir (glob('*.lproj')) {
#            next if $locale_dir =~ /English.lproj/;
            sys_print("rm -rf ./$locale_dir");
        }
    }

    $ENV{CPPFLAGS}="-I$ENV{DSTROOT}$prefix/include -I$prefix/include -DNO_ALLOCA -D__DEBUG__ -D_FORTIFY_SOURCE=2";

    chdir("$ENV{OBJROOT}/kdrive/xorg-server-1.6.0");
    print "Building Xephyr, Xfake, Xnest, and Xvfb\n";

    sys_print("autoreconf -fvi");

    $conf_flags="--disable-dependency-tracking --disable-nls --with-fontdir=$prefix/lib/X11/fonts --with-default-font-path='$ENV{FONTPATH}' --prefix=$prefix --disable-xquartz --enable-kdrive --enable-xfake --enable-xephyr --disable-sdl --enable-xnest --enable-xvfb";
    sys_print( "./configure $conf_flags");
    print "building\n";
    sys_print("make -j".`sysctl -n hw.activecpu`);
    sys_print("make install DESTDIR=$ENV{DSTROOT}");

    chdir("$ENV{OBJROOT}/xinit/xinit-1.1.1");
    print "Building xinit\n";

    sys_print("autoreconf -fvi");

    $conf_flags="--enable-debug --disable-dependency-tracking --disable-nls --with-xinit=$prefix/bin/xinit --prefix=$prefix --with-launchagents-dir=/System/Library/LaunchAgents --with-launchdaemons-dir=/System/Library/LaunchDaemons";
    sys_print( "./configure $conf_flags");
    print "building\n";
    sys_print("make -j".`sysctl -n hw.activecpu`);
    sys_print("make install DESTDIR=$ENV{DSTROOT}");

    chdir("../..");

    sys_print("mkdir $ENV{DSTROOT}$prefix/lib/X11/xinit/xinitrc.d");
    sys_print("ditto xinitrc.d $ENV{DSTROOT}$prefix/lib/X11/xinit/xinitrc.d");
    sys_print("chown -R root:wheel $ENV{DSTROOT}$prefix/lib/X11/xinit");
    sys_print("chmod 755 $ENV{DSTROOT}$prefix/lib/X11/xinit/xinitrc.d/*");

    sys_print("ditto $ENV{OBJROOT}/English.lproj $ENV{DSTROOT}/Applications/Utilities/X11.app/Contents/Resources/English.lproj");
    if($ENV{MACOSFORGE_RELEASE} ne "YES") {
        sys_print("cp $ENV{OBJROOT}/X11.icns $ENV{DSTROOT}/Applications/Utilities/X11.app/Contents/Resources");
    }

    sys_print_nodie("ln -s Xquartz $ENV{DSTROOT}/usr/X11/bin/X");
    make_dsyms();
}

sub get_workdir {
    foreach (glob('*')) {
	return $_ if(-e "$_/configure");
    }
    die "Unable to determine workdir";
}

sub make_dsyms {
    open(FIND,"find $ENV{DSTROOT} -type f -exec file {} +|");
    while(<FIND>) {
	if(/(.*): .*Mach-O/) {
	    $basename=$1;
	    $fullname=$1;
	    $basename =~ s/\/.*\///;
	    sys_print_nodie("dsymutil --out=$ENV{SYMROOT}/$basename.dSYM $fullname");
	    sys_print_nodie("strip -S $fullname");
	}
    }
    close FIND;
}

sub sys_print {
    $command=shift;
    print "$command\n";
    system $command;
    $retval=$? >> 8;
    die "returned code $retval" if $retval;
}

sub sys_print_nodie {
    $command=shift;
    print "$command\n";
    system $command;
    $retval=$? >> 8;
    print "returned code $retval\n" if $retval;
}

sub lipoexec {
    $fname=shift;
    if($ENV{MACOSFORGE_RELEASE} eq "YES") {
        sys_print_nodie("lipo $fname -verify_arch x86_64 && lipo -remove x86_64 -output $fname $fname");
        sys_print_nodie("lipo $fname -verify_arch ppc64 && lipo -remove ppc64 -output $fname $fname");
    } else {
        sys_print_nodie("lipo $fname -verify_arch ppc && lipo -remove ppc -output $fname $fname");
    }
}

