# -*- 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

PortSystem                      1.0

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

set my_name                     minivmac
set my_suffix                   -devel
name                            ${my_name}${my_suffix}
set my_subport                  [regsub -- {-devel$} ${subport} {}]
conflicts                       [lsearch -all -inline -not -exact [list ${my_subport} ${my_subport}-devel] ${subport}]
epoch                           4
version                         37.03
set my_version                  [strsed ${version} {g/^.*-20//}]
categories                      emulators aqua
maintainers                     {ryandesign @ryandesign}
license                         GPL-2
homepage                        http://www.gryphel.org/c/minivmac/beta.html
platforms                       macosx
dist_subdir                     ${my_name}

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

long_description                Mini vMac emulates early Macintosh computers \
                                that use Motorola's 680x0 processors, sold by \
                                Apple from 1984 to 1996.

options my_variations
default my_variations {}

if {${my_subport} eq ${my_name}} {
    PortGroup                   stub 1.0

    stub.subport_name           ${my_subport}
    supported_archs             noarch
    platforms                   any

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

    long_description-append     The best-tested variation emulates a Macintosh \
                                Plus, but it can also emulate a Macintosh \
                                128K, 512K, 512Ke, SE, SE FDHD, Classic, or \
                                Macintosh II.

    revision                    0
    depends_run                 port:${my_name}-plus${my_suffix}

    notes "
        The ${subport} stub port is not meant to be installed. Instead,\
        install one (or more) of the available subports corresponding to the\
        Macintosh model(s) you wish to emulate. Use `port info --subports\
        ${subport}\' to see the list of available subports.
    "
} else {
    livecheck.type              none

    revision                    0
    supported_archs             arm64 i386 ppc x86_64
    distname                    ${my_name}-${my_version}

    master_sites                http://www.gryphel.org/d/minivmac/minivmac-${my_version}/:minivmacsource \
                                sourceforge:project/minivmac/minivmac-extras/extras6:minivmacextras6

    set my_src                  ${distname}.src
    set my_src_distfile         ${my_src}.tgz
    set my_icons                icnsosx-1.0.0
    set my_icons_distfile       ${my_icons}.zip

    distfiles                   ${my_src_distfile}:minivmacsource \
                                ${my_icons_distfile}:minivmacextras6

    extract.only                ${my_src_distfile}

    checksums                   ${my_src_distfile} \
                                rmd160  f9c7ee118db29118e357c2f26d4a3bc7940fba1e \
                                sha256  5f840fa5943dae6dcb6c0d81d1d78381795b89de1efea33e9d819d0a676d1ac7 \
                                size    509172 \
                                ${my_icons_distfile} \
                                rmd160  cef6d7d7578464538d0042b0d98379ae7f18fab7 \
                                sha256  968a0bad51903c9cd3b08476ec5a6572856dc44eedf9ff9b174eb9c59b7b7117 \
                                size    60373

    depends_extract-append      bin:unzip:unzip

    depends_skip_archcheck      unzip

    set my_app_dir              "${applications_dir}/Mini vMac"

    set mnvm_target(arm64)      mcar
    set mnvm_target(i386)       imch
    set mnvm_target(ppc)        mach
    set mnvm_target(x86_64)     mc64

    # Tell the build system what the Xcode version is; theoretically
    # this lets it use flags better suited to that Xcode version.
    if {[info exists xcodeversion]} {
        set xcodeversion_split [concat [split ${xcodeversion} .] {0 0 0}]
        set ide_vers [lindex ${xcodeversion_split} 0][string range [join [lrange ${xcodeversion_split} 1 end] {}] 0 2]
    } else {
        set ide_vers 9410
    }

    # Options that are the same for every variation.
    configure.pre_args          -api cco \
                                -cl \
                                -e xcd \
                                -ev ${ide_vers} \
                                -gse 1 \
                                -homepage https://ports.macports.org/port/${subport} \
                                -maintainer MacPorts \
                                -sony-sum 1 \
                                -sony-tag 1

    # Options set by variations.
    configure.args

    # Options set by variants.
    configure.post_args

    worksrcdir                  ${my_name}
    build.dir                   ${workpath}/build

    post-extract {
        system -W ${workpath} "unzip -q [shellescape ${distpath}/${my_icons_distfile}]"
    }

    post-patch {
        # Use prettier icons.
        foreach icon {App Dsk Rom} {
            move -force ${workpath}/${my_icons}/icons/${icon}Icon.icns \
                ${worksrcpath}/src/ICON[string toupper ${icon}]O.icns
        }
        delete ${workpath}/${my_icons}
    }

    configure {
        xinstall -W ${filespath} configure ${worksrcpath}

        set my_variation_dirs {}

        # Delete remnants from possible previous run.
        delete ${build.dir}

        # Configure all variations.
        foreach my_arch [get_canonical_archs] {
            foreach {my_machine my_variation_options} ${my_variations} {
                set my_variation ${my_version}_${revision}-[strsed [string tolower ${my_machine}] {g/[^a-z0-9_-]//}]-$mnvm_target(${my_arch})

                ui_debug "Configuring ${my_variation}"

                set my_variation_dir ${my_arch}/${my_machine}
                file mkdir ${build.dir}/${my_variation_dir}

                configure.args  -t $mnvm_target(${my_arch}) \
                                -n ${my_variation} \
                                @ \
                                {*}${my_variation_options}

                set all_configure_args [concat ${configure.pre_args} ${configure.args} ${configure.post_args}]

                # Run the configure script.
                system -W ${build.dir}/${my_variation_dir} "CC=[shellescape ${configure.cc}] CFLAGS=[shellescape ${configure.optflags}] [shellescape ${worksrcpath}/configure] ${all_configure_args}"

                lappend my_variation_dirs [strsed ${my_variation_dir} {g/ /\\\\ /}]

                # Use the right compiler.
                reinplace "s|gcc|${configure.cc}|g" ${build.dir}/${my_variation_dir}/Makefile

                # Use the right deployment target.
                reinplace -E {s|-mmacosx-version-min=[0-9.]+||g} ${build.dir}/${my_variation_dir}/Makefile

                # Use the right SDK.
                if {${configure.sdkroot} eq {}} {
                    set sdkflags {}
                } else {
                    set sdkflags "-isysroot${configure.sdkroot}"
                }
                reinplace -E "s|-isysroot *\[^ \]+|${sdkflags}|g" ${build.dir}/${my_variation_dir}/Makefile

                # Prevent merge error.
                if {[variant_exists universal] && [variant_isset universal]} {
                    reinplace "s|$mnvm_target(${my_arch})|umch|" ${build.dir}/${my_variation_dir}/cfg/Info.plist
                }
            }
        }

        # Set up the global Makefile.
        xinstall ${filespath}/Makefile.in ${build.dir}/Makefile
        reinplace "s|@SUBDIRS@|[join ${my_variation_dirs}]|" ${build.dir}/Makefile
    }

    destroot {
        foreach my_arch [get_canonical_archs] {
            if {[variant_exists universal] && [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_exists universal] && [variant_isset universal]} {
            merge ${workpath}/pre-dest
        }
        foreach {my_machine unused} ${my_variations} {
            set my_dest_mnvm_dat "${destroot}${my_app_dir}/Mini vMac ${my_machine}.app/Contents/mnvm_dat"
            destroot.keepdirs-append ${my_dest_mnvm_dat}
        }
    }
}

set default_screen_size         512x342
set default_speed               8x

subport ${my_name}-128k${my_suffix} {
    my_variations               {128K}          {-m 128K}
}

subport ${my_name}-512k${my_suffix} {
    my_variations               {512K}          {-m 128K -mem 512K}
}

subport ${my_name}-512ke${my_suffix} {
    my_variations               {512Ke}         {-m 512Ke}
}

subport ${my_name}-plus${my_suffix} {
    my_variations               {Plus}          {-m Plus}
    default_variants            +icon_master
}

subport ${my_name}-se${my_suffix} {
    my_variations               {SE}            {-m SE}
}

subport ${my_name}-sefdhd${my_suffix} {
    my_variations               {SE FDHD}       {-m SEFDHD}
}

subport ${my_name}-classic${my_suffix} {
    my_variations               {Classic}       {-m Classic}
}

subport ${my_name}-ii${my_suffix} {
    my_variations               {II}            {-m II}
    set default_color_depth     256
    set default_screen_size     640x480
    set default_speed           4x
}

subport ${my_name}-custom${my_suffix} {
    long_description-append     This subport allows the user to compile custom \
                                variations of Mini vMac.

    archive_sites

    set custom_conf_name custom.conf
    set custom_conf ${prefix}/etc/${my_name}/${custom_conf_name}
    set local_custom_conf ${worksrcpath}/${custom_conf_name}

    if {![file exists ${custom_conf}]} {
        known_fail              yes
    }

    pre-configure {
        if {[file exists ${custom_conf}]} {
            copy -force ${custom_conf} ${local_custom_conf}
        } else {
            delete ${local_custom_conf}
        }
        setup_custom_variations
    }

    pre-destroot {
        setup_custom_variations
    }

    proc custom_variation_error {err} {
        global name
        ui_error "For instructions, see"
        ui_error "    https://github.com/macports/macports-ports/blob/master/emulators/${name}/files/README-custom.md"
        return -code error ${err}
    }

    proc add_custom_variation {variation_name variation_options} {
        if {${variation_options} ne {}} {
            my_variations-append ${variation_name} ${variation_options}
        }
    }

    proc setup_custom_variations {} {
        global custom_conf custom_conf_name local_custom_conf filespath
        if {![file exists ${local_custom_conf}]} {
            ui_error "This subport allows you to compile custom variations. Copy"
            ui_error "    ${filespath}/${custom_conf_name}.sample"
            ui_error "to"
            ui_error "    ${custom_conf}"
            ui_error "and then edit ${custom_conf_name}."
            custom_variation_error "missing ${custom_conf_name}"
        }
        my_variations
        set fp [open ${local_custom_conf} r]
        set custom_data [read ${fp}]
        close ${fp}
        set custom_lines [split ${custom_data} "\n"]
        set custom_name {Custom}
        set custom_options {}
        set custom_line_number 0
        set custom_line_continue no
        foreach custom_line ${custom_lines} {
            incr custom_line_number
            if {[regexp -- {^\s*[;#]} ${custom_line}]} {
                continue
            } elseif {${custom_line_continue}} {
                set custom_line_continue [regsub -- {^(.*)\\$} ${custom_line} {\1} custom_line]
                append custom_${custom_key} " [string trim ${custom_line}]"
            } elseif {[regexp -- {^([^=]+)=(.*)$} ${custom_line} -> custom_key custom_value]} {
                set custom_line_continue [regsub -- {^(.*)\\$} ${custom_value} {\1} custom_value]
                set custom_key [string trim ${custom_key}]
                set custom_${custom_key} [string trim ${custom_value}]
            } elseif {[regexp -- {^\s*\[([^\]]+)\]\s*$} ${custom_line} -> new_custom_name]} {
                add_custom_variation ${custom_name} ${custom_options}
                set custom_name ${new_custom_name}
                set custom_options {}
            } elseif ![regexp -- {^\s*$} ${custom_line}] {
                ui_error "Syntax error on line ${custom_line_number} of ${custom_conf_name}: '${custom_line}'"
                custom_variation_error "syntax error in ${custom_conf_name}"
            }
        }
        add_custom_variation ${custom_name} ${custom_options}
        if {[option my_variations] eq {}} {
            ui_error "No custom variations defined in ${custom_conf_name}."
            custom_variation_error "no variations in ${custom_conf_name}"
        }
    }
}

if {${my_subport} ni [list "${my_name}" "${my_name}-custom"]} {
    description                 a Macintosh [lindex ${my_variations} 0] emulator

    long_description-append     This subport emulates a Macintosh \
                                [lindex ${my_variations} 0].

    if {[lindex ${my_variations} 0] eq "Plus"} {
        long_description-append This is the best-tested variation.
    }

    long_description-append     There are other subports that emulate other Macintosh \
                                models.

    variant icon_master description {Take ownership of disk image files and ROM image files; at most one copy of Mini vMac should do this} {
        configure.post_args-append \
                                -im 1
    }

    variant min_extensions description {Disable extensions not needed for most situations, including clipboard import/export and file/disk image creation} {
        configure.post_args-append \
                                -min-extn
    }

    if {${my_subport} eq "${my_name}-ii"} {
        set color_depths {
            0   bw          {Black and white only}
            1   4           {4 colors or black and white}
            2   16          {16 colors or black and white}
            3   256         {256 colors or black and white}
            4   thousands   {Thousands of colors or black and white}
            5   millions    {Millions of colors or black and white}
        }
        foreach {color_depth color_depth_name color_depth_description} ${color_depths} {
            lappend color_depth_variants colors_${color_depth_name}
        }
        set set_default_color_depth_variant yes
        foreach {color_depth color_depth_name color_depth_description} ${color_depths} {
            set color_depth_variant colors_${color_depth_name}
            variant ${color_depth_variant} conflicts {*}[lsearch -all -inline -not -exact ${color_depth_variants} ${color_depth_variant}] description ${color_depth_description} "
                configure.post_args-append  -depth ${color_depth}
            "
            if {[variant_isset ${color_depth_variant}]} {
                set set_default_color_depth_variant no
            }
        }
        if {${set_default_color_depth_variant}} {
            default_variants +colors_${default_color_depth}
        }
    }

    set screen_sizes {512x342 512x384}
    if {${my_subport} ne "${my_name}-128k"} {
        lappend screen_sizes 640x480 800x600 1024x768
    }
    foreach screen_size ${screen_sizes} {
        lappend screen_size_variants screen_${screen_size}
    }
    set set_default_screen_size_variant yes
    foreach screen_size ${screen_sizes} {
        set screen_hres [lindex [split ${screen_size} {x}] 0]
        set screen_vres [lindex [split ${screen_size} {x}] 1]
        set screen_size_variant screen_${screen_size}
        variant ${screen_size_variant} conflicts {*}[lsearch -all -inline -not -exact ${screen_size_variants} ${screen_size_variant}] description "Screen size ${screen_size}" "
            configure.post_args-append  -hres ${screen_hres} -vres ${screen_vres}
        "
        if {[variant_isset ${screen_size_variant}]} {
            set set_default_screen_size_variant no
        }
    }
    if {${set_default_screen_size_variant}} {
        default_variants +screen_${default_screen_size}
    }

    set speeds {z 1x 1 2x 2 4x 3 8x 4 16x 5 32x a unlimited}
    foreach {speed speed_name} ${speeds} {
        lappend speed_variants speed_${speed_name}
    }
    set set_default_speed_variant yes
    foreach {speed speed_name} ${speeds} {
        set speed_variant speed_${speed_name}
        variant ${speed_variant} conflicts {*}[lsearch -all -inline -not -exact ${speed_variants} ${speed_variant}] description "Default CPU speed ${speed_name}" "
            configure.post_args-append  -speed ${speed}
        "
        if {[variant_isset ${speed_variant}]} {
            set set_default_speed_variant no
        }
    }
    if {${set_default_speed_variant}} {
        default_variants +speed_${default_speed}
    }
}
