#!/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('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};
    $ENV{DESTDIR}=$ENV{DSTROOT};

    $ACLOCAL_LOCALDIR="$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";
    $ENV{LIBTOOLIZE}="/usr/bin/glibtoolize";
    
# The following is required to make pkg-config find our .pc metadata files
    $ENV{PKG_CONFIG_PATH}="$prefix/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 .= "-arch $arch ";
	$arch_flags_32 .= " -arch $arch " unless $arch =~ /64/;
    }
    
    $ENV{CFLAGS}="-I$ENV{DSTROOT}$prefix/include -I$prefix/include -DNO_ALLOCA -D__DEBUG__ -g3 -pipe $arch_flags";
    $ENV{OBJCFLAGS}="$ENV{CFLAGS}";
    $ENV{LDFLAGS}="-L$ENV{DSTROOT}$prefix/lib -L$prefix/lib -pipe $arch_flags";
    
    $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-6.5.2");
    sys_print("make");
    sys_print("mkdir -p $ENV{DSTROOT}$prefix/lib");
    sys_print("mkdir -p $ENV{DSTROOT}$prefix/include/GL");

    sys_print("/usr/bin/install_name_tool -id $prefix/lib/libGL.1.dylib lib/libGL.1.dylib");

#    sys_print("/usr/bin/install_name_tool -id $prefix/lib/libOSMesa.4.dylib lib/libOSMesa.6.dylib");
#    sys_print("/usr/bin/install_name_tool -change libGL.1.dylib $prefix/lib/libGL.1.dylib lib/libOSMesa.6.dylib");

    sys_print("/usr/bin/install_name_tool -id $prefix/lib/libGLU.1.dylib lib/libGLU.1.dylib");
    sys_print("/usr/bin/install_name_tool -change libGL.1.dylib $prefix/lib/libGL.1.dylib lib/libGLU.1.dylib");

#    sys_print("/usr/bin/install_name_tool -id $prefix/lib/libglut.3.dylib lib/libglut.3.dylib");
#    sys_print("/usr/bin/install_name_tool -change libGLU.1.dylib $prefix/lib/libGLU.1.dylib lib/libglut.3.7.dylib");
#    sys_print("/usr/bin/install_name_tool -change libGL.1.dylib $prefix/lib/libGL.1.dylib lib/libglut.3.7.dylib");

#    sys_print("/usr/bin/install_name_tool -change libGL.1.dylib $prefix/lib/libGL.1.dylib progs/xdemos/glxgears");
#    sys_print("/usr/bin/install_name_tool -change libGLU.1.dylib $prefix/lib/libGLU.1.dylib progs/xdemos/glxgears");
#    sys_print("/usr/bin/install_name_tool -change libglut.3.dylib $prefix/lib/libglut.3.dylib progs/xdemos/glxgears");

#    sys_print("/usr/bin/install_name_tool -change libGL.1.dylib $prefix/lib/libGL.1.dylib progs/xdemos/glxinfo");
#    sys_print("/usr/bin/install_name_tool -change libGLU.1.dylib $prefix/lib/libGLU.1.dylib progs/xdemos/glxinfo");
#    sys_print("/usr/bin/install_name_tool -change libglut.3.dylib $prefix/lib/libglut.3.dylib progs/xdemos/glxinfo");

    sys_print("ditto lib $ENV{DSTROOT}$prefix/lib");
    sys_print("ditto include/GL $ENV{DSTROOT}$prefix/include/GL");
#    lipo64("progs/xdemos/glxgears");
#    sys_print("cp progs/xdemos/glxgears $ENV{DSTROOT}$prefix/bin");
#    lipo64("progs/xdemos/glxinfo");
#    sys_print("cp progs/xdemos/glxinfo $ENV{DSTROOT}$prefix/bin");
    sys_print("rm -rf $ENV{DSTROOT}$prefix/include/GL/internal");
    sys_print("chown -R root:wheel $ENV{DSTROOT}$prefix/include/GL/*");
    sys_print("ln -s libGLU.1.dylib $ENV{DSTROOT}$prefix/lib/libGLU.1.3.dylib");
    sys_print("ln -s libGL.1.dylib $ENV{DSTROOT}$prefix/lib/libGL.1.2.dylib");
    sys_print("chown -R root:wheel $ENV{DSTROOT}$prefix/lib");

    chdir("$ENV{OBJROOT}/libGL");
    sys_print("make -j".`sysctl -n hw.activecpu`);
#    sys_print("cp $ENV{DSTROOT}$prefix/lib/libGL.1.2.dylib $ENV{DSTROOT}$prefix/lib/libGL.1.2.dylib-x86-dri");
    sys_print("cp GL/libGL.1.2.dylib $ENV{DSTROOT}$prefix/lib");
    sys_print("cp mesa/OSmesa/libOSMesa.4.dylib $ENV{DSTROOT}$prefix/lib/");
    sys_print("ln -s libOSMesa.4.dylib $ENV{DSTROOT}$prefix/lib/libOSMesa.4.0.dylib");
    sys_print("ln -s libOSMesa.4.dylib $ENV{DSTROOT}$prefix/lib/libOSMesa.dylib");

    $ENV{CFLAGS}="-I$ENV{DSTROOT}$prefix/include -I$prefix/include -DNO_ALLOCA -D__DEBUG__ -g3 -pipe $arch_flags_32 ";
    $ENV{OBJCFLAGS}="$ENV{CFLAGS}";
    $ENV{LDFLAGS}="-L$ENV{DSTROOT}$prefix/lib -L$prefix/lib -pipe $arch_flags_32";

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

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

    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");
    }

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

    $conf_flags="--with-mesa-source=$ENV{OBJROOT}/mesa/Mesa-7.0.3 --enable-debug --disable-dependency-tracking --disable-nls --with-fontdir=/usr/X11/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 --mandir=$prefix/man ";
    sys_print( "./configure $conf_flags");
    print "building\n";
    sys_print("make -j".`sysctl -n hw.activecpu`);
    sys_print("make install");

    $ENV{LDFLAGS}="$ENV{LDFLAGS} -framework CoreServices ";

    chdir("$ENV{OBJROOT}/xinit/xinit-1.1.0");
    print "Building xinit\n";
    $conf_flags="--enable-debug --disable-dependency-tracking --disable-nls --with-fontdir=/usr/X11/lib/X11/fonts --prefix=$prefix --with-launchagents-dir=/System/Library/LaunchAgents --with-launchdaemons-dir=/System/Library/LaunchDaemons --mandir=$prefix/man ";
    sys_print( "./configure $conf_flags");
    print "building\n";
    sys_print("make -j".`sysctl -n hw.activecpu`);
    sys_print("make install");

    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");
    sys_print("cp $ENV{OBJROOT}/X11.icns $ENV{DSTROOT}/Applications/Utilities/X11.app/Contents/Resources");

# move X11.app into place
    sys_print_nodie("rm $ENV{DSTROOT}/Application/Utilities/X11.app/Contents/Resources/Info.plist");
    lipo64("$ENV{DSTROOT}/Applications/Utilities/X11.app/Contents/MacOS/X11");
    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 lipo64 {
    $fname=shift;
    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");
}

