# -*- coding: utf-8; mode: tcl; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:ft=tcl:et:sw=4:ts=4:sts=4
# $Id: Portfile 106506 2013-05-28 21:35:18Z ryandesign@macports.org $

PortSystem              1.0

# Please keep the minivmac and minivmac-devel ports as similar as possible.

name                    minivmac-devel
conflicts               minivmac
set my_name             minivmac
epoch                   3
version                 3.3.2
revision                1
set branch              [join [lrange [split ${version} .] 0 1] .]
set my_version          [strsed ${version} {g/^20//}]
categories              emulators aqua
maintainers             ryandesign
license                 GPL-2
homepage                http://minivmac.sourceforge.net/
use_zip                 yes
platforms               macosx
use_parallel_build      yes
dist_subdir             ${my_name}
if {${version} != ${my_version}} {
    # Development versions:
    distname            ${my_name}${my_version}
} else {
    # Alpha and beta versions:
    distname            ${my_name}-${version}
}

description             an emulator of the Macintosh Plus and other early Macintosh models

long_description        The Mini vMac emulator helps preserve software made for early \
                        Macintosh computers -- those sold by Apple from 1984 to 1996 \
                        based on Motorola's 680x0 microprocessors. \
                        The best-tested version emulates a Macintosh Plus, but there are \
                        also emulations of the Macintosh 128K, 512K, 512Ke, SE, Classic, \
                        and SE FDHD, and work on Macintosh II emulation is in progress.

master_sites            sourceforge:project/minivmac/minivmac/${version}:minivmacsource \
                        sourceforge:project/minivmac/minivmac-extras/extras6:minivmacextras6 \
                        http://www.ryandesign.com/macports/distfiles/minivmac:bootstrap \
                        http://download.info.apple.com/Apple_Support_Area/Apple_Software_Updates/English-North_American/Macintosh/System/Older_System/System_7.0.x/:apple

set my_src                                  ${distname}.src
set my_src_distfile                         ${my_src}.zip
set my_bootstrap_distfile                   ${my_name}-bootstrap-3.2.3_0.zip
set my_icons                                icnsosx-1.0.0
set my_icons_distfile                       ${my_icons}.zip
set my_system_disk_container                System_7.0.1.smi
set my_system_disk_container_distfile       ${my_system_disk_container}.bin

distfiles               ${my_src_distfile}:minivmacsource \
                        ${my_bootstrap_distfile}:bootstrap \
                        ${my_icons_distfile}:minivmacextras6 \
                        ${my_system_disk_container_distfile}:apple

extract.only            ${my_src_distfile} \
                        ${my_bootstrap_distfile} \
                        ${my_icons_distfile}

checksums               ${my_src_distfile} \
                        rmd160  a8a75847ed43a4d830930a98e3a20a2451144350 \
                        sha256  b5a02693a6106585622f2f928371f160c9b79656b834e7e25519de2d645eb1be \
                        ${my_bootstrap_distfile} \
                        rmd160  32e803a75d4f9ab6b7dfa5a7b1ec2ef9d3a057c2 \
                        sha256  e6fe692683ab54e08b0350fe9901e872f7bf3c3a62f69b45773254fce45a4fae \
                        ${my_icons_distfile} \
                        md5     2af006506de7549be14f94317918d59a \
                        sha1    4ef79bb56b988fedfeb82a8b6cafd8066f5bbab2 \
                        rmd160  cef6d7d7578464538d0042b0d98379ae7f18fab7 \
                        ${my_system_disk_container_distfile} \
                        md5     8a4776350b15b5a516cdf7dd18e27290 \
                        sha1    d4c8b8653de9c7a9b2594dd6126ec7120e3e2e9e \
                        rmd160  89fc3780c9c5d575a8da4068dc810c1f56c70211

depends_extract         port:bsdiff

set my_app_dir          "${applications_dir}/Mini vMac"
set my_rom_dir          "~/Library/Preferences/Gryphel/mnvm_rom"
set my_bootstrap_app    "Mini vMac Bootstrap.app"
set my_rom_file         vMac.ROM
set my_base_options     "-maintainer MacPorts -homepage http://www.macports.org/ -cl -eol unx -sony-sum 1 -sony-tag 1"
set my_archs            {}

options my_variations
my_variations           {128K}      {-m 128K} \
                        {512K}      {-m 128K -mem 512K} \
                        {512Ke}     {-m 512Ke} \
                        {Plus}      {-m Plus -im 1} \
                        {SE}        {-m SE} \
                        {SE FDHD}   {-m SEFDHD} \
                        {Classic}   {-m Classic}

variant unsupported description {Also build unfinished Macintosh II and IIx emulators} {
    my_variations-append \
                        {II}        {-m II -mem 8M -hres 800 -vres 600 -depth 3} \
                        {IIx}       {-m IIx -mem 8M -hres 800 -vres 600 -depth 3}
}

# To build the bootstrap, use "sudo port install bootstrap=yes +bootstrap".
# The variant is hidden because it is useful only to the port maintainer.
if {[tbool bootstrap]} {
    variant bootstrap conflicts unsupported requires universal description {Build the bootstrap version of Mini vMac} {
        my_variations   {Bootstrap} {-m Plus -sound 0 -bg 1 -speed a -as 0}
        depends_build-append port:p7zip
        depends_skip_archcheck p7zip
        post-destroot {
            exec 7za a ${destroot}${my_app_dir}/${my_name}-bootstrap-${version}_${revision}.zip ${destroot}${my_app_dir}/${my_bootstrap_app}
        }
    }
    default_variants +bootstrap
}

variant universal {
    configure.universal_args
    configure.universal_archs ppc i386
    set my_archs ${configure.universal_archs}
}
supported_archs         i386 ppc
if {![variant_isset universal]} {
    set my_archs ${configure.build_arch}
}

pre-extract {
    if {"" == [my_real_rom_file]} {
        ui_msg "****************************************************************"
        ui_msg "To build Mini vMac, you will need a ROM file from a Macintosh"
        ui_msg "Plus or 512Ke. And to run it, you need a ROM file from the type"
        ui_msg "of Mac you want to emulate. ROM files are not included with this"
        ui_msg "package because they are copyrighted Apple software."
        ui_msg "To create a ROM file, download the CopyRoms program from"
        ui_msg "${homepage}extras/copyroms.html"
        ui_msg "and transfer it to a real physical early Macintosh that you own."
        ui_msg "Run the CopyRoms program there, then transfer the ROM file back"
        ui_msg "to this Mac and put it in ${my_rom_dir}"
        ui_msg "(which can be an alias or symlink if desired) or"
        ui_msg "${my_app_dir}."
        ui_msg "****************************************************************"
        return -code error "${my_rom_file} not found"
    }
}

worksrcdir              configure
build.dir               ${workpath}/build
extract.mkdir           yes
extract.asroot          yes

post-extract {
    # Decompress the system disk container image.
    ui_debug "Decompressing ${my_system_disk_container_distfile}."
    set my_system_disk_container_decompressed "[file rootname ${my_system_disk_container}].dmg"
    system -W ${worksrcpath} "hdiutil convert '${distpath}/${my_system_disk_container_distfile}' -format UDRO -o '${my_system_disk_container_decompressed}'"
    
    # The images on the container image. Images we don't need are commented out for future reference.
    set my_images {
        {Disk Tools.image}    58368 eb1979132c843560ebab490faeb7520d9a94757ecef3121a21abace8d3ae63ff
        {Tidbits.image}     1902848 3e3600bed1b5c7c595bc176b5eaadcc8c1517032489efc548b9b781c0ee1f062
    }
#        {Fonts.image}        427264 8b06f086a96b75bd23b16ae018bd334696239cb56e65bfa20166ea00d14cdef0
#        {Install 1.image}    796160 8c3ea898eeb88b795041108cd8a09bf4ebdf920d7d4763e4419df14713dbd952
#        {Install 2.image}   1165056 0fc558475df55f3aed217d2eceebfa29e4a465a795807cd627b258740a9ec55b
#        {Printing.image}    1533952 246cbf69ad1c2e588ee482fddec781135a67fbfe02734bb0f732eb055faa15fa
    
    # Extract the disk images from the system disk container image. `hdiutil` on OS X 10.8 Mountain Lion
    # does not mount this disk image correctly, so extract the files manually using `dd`.
    foreach {my_image_filename my_image_offset my_image_sha256} ${my_images} {
        ui_debug "Extracting ${my_image_filename} from ${my_system_disk_container_decompressed}."
        system -W ${worksrcpath} "dd if='${my_system_disk_container_decompressed}' bs=4 count=368661 skip=${my_image_offset} of='${my_image_filename}'"
        if {${my_image_sha256} != [sha256 file ${worksrcpath}/${my_image_filename}]} {
            return -code error "extract failed"
        }
    }
    
    # Delete temporary files we no longer need.
    delete ${worksrcpath}/${my_system_disk_container_decompressed}
    
    # Make the data directory, where Mini vMac looks for the files it needs.
    set my_mnvm_dat "${worksrcpath}/${my_bootstrap_app}/Contents/mnvm_dat"
    file mkdir ${my_mnvm_dat}
    
    # Symlink the ROM file into the data directory.
    ln -s [my_real_rom_file] ${my_mnvm_dat}
    
    # Symlink the disk images into the data directory with sequentially-numbered
    # names so Mini vMac will find them and automatically mount them.
    ln -s "${worksrcpath}/Disk Tools.image" "${my_mnvm_dat}/disk1.dsk"
    ln -s ${worksrcpath}/Tidbits.image "${my_mnvm_dat}/disk2.dsk"
    ln -s ${worksrcpath}/${my_src}/${my_src}.dsk "${my_mnvm_dat}/disk3.dsk"
    
    # Use the prettier icon on the bootstrap app.
    copy -force ${worksrcpath}/${my_icons}/icons//AppIcon.icns ${worksrcpath}/${my_bootstrap_app}/Contents/Resources/
}

post-patch {
    # Place an 8192-byte TeachText file called "configure.args" (containing "@START@",
    # 8180 spaces, and "@END@") onto the Tidbits disk.
    system -W ${worksrcpath} "${prefix}/bin/bspatch Tidbits.image Tidbits.image.in '${filespath}/patch-Tidbits.image.bsdiff'"
    
    # Place an alias of the configure.args file in the Startup Items folder on the Disk Tools disk.
    system -W ${worksrcpath} "${prefix}/bin/bspatch 'Disk Tools.image' 'Disk Tools.image.tmp' '${filespath}/patch-Disk Tools.image.bsdiff'"
    move -force "${worksrcpath}/Disk Tools.image.tmp" "${worksrcpath}/Disk Tools.image"
}

pre-configure {
    # Set the name of the bootstrap app in the configure script.
    xinstall -m 755 ${filespath}/configure.applescript.in ${worksrcpath}/configure.applescript
    reinplace "s|@BOOTSTRAP_APP@|${my_bootstrap_app}|g" ${worksrcpath}/configure.applescript
    
    # Copy the template Tidbits disk image.
    copy -force ${worksrcpath}/Tidbits.image.in ${worksrcpath}/Tidbits.image
    
    # Build up the combined configure args for all variations.
    set i 0
    foreach my_arch ${my_archs} {
        set my_target [my_arch_to_target ${my_arch}]
        foreach {my_machine my_variation_options} ${my_variations} {
            if {${i} > 0} {
                lappend configure_args \;
            }
            lappend configure_args \
                ${my_base_options} \
                -t ${my_target} \
                ${my_variation_options} \
                -n ${version}_${revision}-[strsed [string tolower ${my_machine}] {g/[^a-z0-9_-]//}]-${my_target}
            incr i
        }
    }
    
    # Write the configure args into the configure.args file on the Tidbits disk image.
    set max_configure_args_length 8192
    set padded_args [format "%-${max_configure_args_length}s" [join ${configure_args}]]
    if {[string length ${padded_args}] > ${max_configure_args_length}} {
        return -code error "configure args too long"
    }
    reinplace -locale C "s|@START@ *@END@|${padded_args}|" ${worksrcpath}/Tidbits.image
    
    # Set the real configure.args that get passed to the AppleScript to the number
    # of variations being assembled, so that it knows how long to wait.
    configure.args ${i}
    
    # Launch the bootstrap Mini vMac so the configure AppleScript can talk to it.
    global my_bootstrap_pid
    if {[catch {exec "${worksrcpath}/${my_bootstrap_app}/Contents/MacOS/minivmac" &} my_bootstrap_pid]} {
        return -code error "couldn't launch bootstrap"
    }
}

configure.cmd           osascript
configure.pre_args      ./configure.applescript

post-configure {
    # Kill the bootstrap Mini vMac.
    global my_bootstrap_pid
    exec kill ${my_bootstrap_pid}
    
    file mkdir ${build.dir}
    set my_variation_dirs {}
    foreach my_arch ${my_archs} {
        file mkdir ${build.dir}/${my_arch}
        set my_target [my_arch_to_target ${my_arch}]
        foreach {my_machine unused} ${my_variations} {
            set my_variation ${version}_${revision}-[strsed [string tolower ${my_machine}] {g/[^a-z0-9_-]//}]-${my_target}
            set my_src_tarball ${worksrcpath}/${my_variation}.tar
            if {[file isfile ${my_src_tarball}]} {
                set my_variation_dir ${my_arch}/${my_machine}
                lappend my_variation_dirs [strsed ${my_variation_dir} {g/ /\\\\ /}]
                
                # Untar the configured source code.
                system -W ${build.dir} "tar xf '${my_src_tarball}'"
                move ${build.dir}/${my_variation} ${build.dir}/${my_variation_dir}
                
                if {[variant_exists bootstrap] && [variant_isset bootstrap]} {
                    # Change the "export" function so that exported files are written to the same
                    # directory as Mini vMac, instead of prompting for a location.
                    system -W ${build.dir}/${my_variation_dir} "patch -p0 < ${filespath}/patch-src-MYOSGLUE.c.diff"
                }
                
                # Use the right compiler.
                reinplace "s|gcc|${configure.cc}|g" ${build.dir}/${my_variation_dir}/Makefile
                
                # Remove references to SDKs -- the 10.4u SDK is not installed by default on 10.6
                # and even if you install it manually it does not work here.
                reinplace -E {s|-isysroot /Developer/SDKs/[^ ]+||g} ${build.dir}/${my_variation_dir}/Makefile
            }
        }
    }
    
    # Set up the global Makefile.
    xinstall ${filespath}/Makefile.in ${build.dir}/Makefile
    reinplace "s|@SUBDIRS@|[join ${my_variation_dirs}]|" ${build.dir}/Makefile
    
    # If no variation directories were produced by configuration, either the flags we
    # passed in were bad, or the automation script got out of sync with the emulator;
    # if the latter, the delays in configure.applescript may need to be adjusted.
    if {"" == ${my_variation_dirs}} {
        return -code error "configuration failed!"
    }
}

set my_share_dir        ${prefix}/share/${my_name}

post-build {
    set i 0
    foreach my_arch ${my_archs} {
        set my_target [my_arch_to_target ${my_arch}]
        foreach {my_machine unused} ${my_variations} {
            if {[variant_isset universal]} {
                reinplace "s|${my_target}|umch|" ${build.dir}/${my_arch}/${my_machine}/minivmac.app/Contents/Info.plist
            }
            if {![variant_exists bootstrap] || ![variant_isset bootstrap]} {
                # To save space, keep only a single copy of the Resources directory.
                set my_resources_dir ${build.dir}/${my_arch}/${my_machine}/minivmac.app/Contents/Resources
                if {0 == ${i}} {
                    move ${my_resources_dir} ${build.dir}
                } else {
                    delete ${my_resources_dir}
                }
                ln -s ${my_share_dir}/Resources ${my_resources_dir}
            }
            incr i
        }
    }
    
    if {![variant_exists bootstrap] || ![variant_isset bootstrap]} {
        # Install the prettier icons.
        eval xinstall -m 644 [glob ${worksrcpath}/${my_icons}/icons/*.icns] ${build.dir}/Resources
    }
}

destroot {
    if {![variant_exists bootstrap] || ![variant_isset bootstrap]} {
        # Install the global Resources directory.
        xinstall -d ${destroot}${my_share_dir}
        copy ${build.dir}/Resources ${destroot}${my_share_dir}
    }
    
    # Install the programs.
    foreach my_arch ${my_archs} {
        if {[variant_isset universal]} {
            set my_dest ${workpath}/pre-dest/${my_arch}
        } else {
            set my_dest ${destroot}
        }
        xinstall -d ${my_dest}${my_app_dir}
        foreach {my_machine unused} ${my_variations} {
            copy ${build.dir}/${my_arch}/${my_machine}/minivmac.app \
                "${my_dest}${my_app_dir}/Mini vMac ${my_machine}.app"
        }
    }
    if {[variant_isset universal]} {
        merge ${workpath}/pre-dest
    }
}

# Returns the full path to the ROM file, wherever the user has it,
# or the empty string if the user doesn't have it.
proc my_real_rom_file {} {
    global my_app_dir my_rom_dir my_rom_file
    if {[file exists ${my_app_dir}/${my_rom_file}]} {
        return ${my_app_dir}/${my_rom_file}
    }
    set my_real_rom_dir [my_read_alias ${my_rom_dir}]
    if {[file exists ${my_real_rom_dir}/${my_rom_file}]} {
        return ${my_real_rom_dir}/${my_rom_file}
    }
    return ""
}

# Resolves a Mac OS X alias.
proc my_read_alias {file} {
    global filespath
    return [exec osascript ${filespath}/readalias.applescript [file normalize ${file}]]
}

# Converts normal arch names into Mini vMac target names.
proc my_arch_to_target {arch} {
    switch ${arch} {
        i386 {
            return imch
        }
        ppc {
            return mach
        }
        default {
            return -code error "unsupported architecture ${arch}"
        }
    }
}

livecheck.type          regex
livecheck.version       ${my_version}
livecheck.regex         ${my_name}-?(\[0-9.\]+)\\.src

if {${version} != ${my_version}} {
    # Development versions:
    livecheck.url       ${homepage}develop/index.html
} else {
    # Alpha versions:
    livecheck.url       ${homepage}doc-${branch}/download.html
    
    # Beta versions:
    #livecheck.url       ${homepage}beta/index.html
}
