# -*- 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
PortGroup           app 1.0
PortGroup           meson 1.0

name                virt-viewer
version             11.0
revision            4
categories          emulators
maintainers         {dports @drkp} openmaintainer
license             GPL-2+

homepage            https://virt-manager.org
master_sites        https://releases.pagure.org/virt-viewer/

description         connects to VMs via VNC/SPICE and libvirt
long_description    \
    Virtual Machine Viewer provides a graphical console client for connecting \
    to virtual machines. It uses the GTK-VNC or SPICE-GTK widgets to provide \
    the display, and libvirt for looking up VNC/SPICE server details.

use_xz              yes

checksums           rmd160  d16895408be0b3fa29bbf7854d5e83030e845408 \
                    sha256  a43fa2325c4c1c77a5c8c98065ac30ef0511a21ac98e590f22340869bad9abd0 \
                    size    259772

patchfiles          patch-data-meson-build.diff

# Python version used at build time; meson.build invokes python3.
set py_branch       3.14
set py_version      [string map {. {}} ${py_branch}]

depends_build-append \
                    port:gettext \
                    port:makeicns \
                    path:bin/pkg-config:pkgconfig \
                    port:python${py_version}

depends_lib-append  path:lib/pkgconfig/gdk-pixbuf-2.0.pc:gdk-pixbuf2 \
                    port:gettext-runtime \
                    path:lib/pkgconfig/glib-2.0.pc:glib2 \
                    port:gtk-vnc \
                    path:lib/pkgconfig/gtk+-3.0.pc:gtk3 \
                    port:libvirt \
                    port:libvirt-glib \
                    port:libxml2 \
                    path:lib/pkgconfig/pango.pc:pango \
                    port:spice-gtk \
                    port:spice-protocol

depends_run-append  port:desktop-file-utils

# Type redefinition
compiler.c_standard 2011

# Pin every optional meson feature to avoid opportunistic dependencies.
# spice-protocol is added above because spice-gtk's spice-client-glib-2.0.pc
# requires it but only build-depends on it.
# https://trac.macports.org/ticket/74206
# ovirt is disabled because there is no govirt port to satisfy it.
configure.args-append \
                    -Dbash_completion=disabled \
                    -Dlibvirt=enabled \
                    -Dovirt=disabled \
                    -Dspice=enabled \
                    -Dvnc=enabled \
                    -Dvte=disabled

variant bash_completion {
    depends_build-append    port:bash-completion
    configure.args-replace  -Dbash_completion=disabled -Dbash_completion=enabled
}

variant vte description "Support virtual machine serial/text consoles via VTE" {
    depends_lib-append      port:vte
    configure.args-replace  -Dvte=disabled -Dvte=enabled
}

default_variants    +bash_completion +vte

# meson.build looks up the unversioned "python3", which MacPorts provides only
# via "port select"; point find_program at the versioned interpreter.
# The reinplace works around upstream calling run_command() with the "python3"
# string instead of the program found above.
# https://trac.macports.org/ticket/71963
configure.python    ${prefix}/bin/python${py_branch}
meson.native.binaries-append \
                    python3=${configure.python}
post-patch {
    reinplace "s|'python3', '-c'|python3, '-c'|g" ${worksrcpath}/meson.build

    fs-traverse f ${worksrcpath}/build-aux {
        if {[string match *.py ${f}]} {
            reinplace -q "s|/usr/bin/python3|${configure.python}|" ${f}
            reinplace -q "s|/usr/bin/env python3|${configure.python}|" ${f}
        }
    }
}

# TODO: move this inside a variant.

# Build a MacOS app bundle that launches remote-viewer. This is
# a little more complicated because we have to use an AppleScript
# droplet suitable for registering as a handler for .vv connection
# files. The AppleScript copies the file to a temporary directory in
# case the original is in a quarantined location, and deletes the
# original if delete-this-file is set (just like remote-viewer would do).

app.name            Remote Viewer
app.identifier      org.macports.remote-viewer
app.executable      ${prefix}/bin/remote-viewer
app.retina          yes
app.use_launch_script no

variant app_as_root description "Applet launches Remote Viewer with admin privileges (insecure, required for usb forwarding)" {}

post-patch {
    set scriptfile ${workpath}/RemoteViewer.applescript
    copy ${filespath}/RemoteViewer.applescript ${scriptfile}

    reinplace "s|@PREFIX@|${prefix}|g" ${scriptfile}

    if {[variant_isset app_as_root]} {
        reinplace "s|@PRIVILEGES@| with administrator privileges|g" ${scriptfile}
    } else {
        reinplace "s|@PRIVILEGES@||g" ${scriptfile}
    }
}

post-build {
    # Build an .icns icon from source PNGs using makeicns.
    set icns_args {}
    foreach size {16 32 128 256 512} {
        set src ${worksrcpath}/icons/${size}x${size}/virt-viewer.png
        if {[file exists ${src}]} {
            lappend icns_args "-${size} [shellescape ${src}]"
        }
    }
    system "${prefix}/bin/makeicns [join ${icns_args}] -out [shellescape ${workpath}/virt-viewer.icns]"
}

app.icon            ${workpath}/virt-viewer.icns

post-destroot {
    set app_root ${destroot}${applications_dir}/${app.name}.app
    set applet ${workpath}/RemoteViewer-applet.app

    # Compile the AppleScript into an applet.
    if {[file exists ${applet}]} {
        delete -force ${applet}
    }
    system "/usr/bin/osacompile -o [shellescape ${applet}] [shellescape ${workpath}/RemoteViewer.applescript]"

    # Replace the app bundle payload with the compiled AppleScript applet.
    delete -force ${app_root}/Contents/MacOS
    copy ${applet}/Contents/MacOS ${app_root}/Contents/

    delete -force ${app_root}/Contents/Resources
    copy ${applet}/Contents/Resources ${app_root}/Contents/

    # Copy the icon into Resources.
    copy ${workpath}/virt-viewer.icns ${app_root}/Contents/Resources/virt-viewer.icns

    # Replace plist with osacompile's (has proper applet keys), then customize.
    delete -force ${app_root}/Contents/Info.plist
    copy ${applet}/Contents/Info.plist ${app_root}/Contents/Info.plist

    set plist ${app_root}/Contents/Info.plist
    set pb "/usr/libexec/PlistBuddy"
    system "${pb} -c 'Delete :CFBundleIdentifier' [shellescape ${plist}]; true"
    system "${pb} -c 'Add :CFBundleIdentifier string ${app.identifier}' [shellescape ${plist}]"
    system "${pb} -c 'Delete :CFBundleName' [shellescape ${plist}]; true"
    system "${pb} -c 'Add :CFBundleName string ${app.name}' [shellescape ${plist}]"
    system "${pb} -c 'Delete :CFBundleIconFile' [shellescape ${plist}]; true"
    system "${pb} -c 'Add :CFBundleIconFile string virt-viewer.icns' [shellescape ${plist}]"
    system "${pb} -c 'Delete :CFBundleShortVersionString' [shellescape ${plist}]; true"
    system "${pb} -c 'Add :CFBundleShortVersionString string ${version}' [shellescape ${plist}]"
    system "${pb} -c 'Delete :CFBundleDocumentTypes' [shellescape ${plist}]; true"
    system "${pb} \
        -c 'Add :CFBundleDocumentTypes array' \
        -c 'Add :CFBundleDocumentTypes:0 dict' \
        -c 'Add :CFBundleDocumentTypes:0:CFBundleTypeName string Virt Viewer Connection File' \
        -c 'Add :CFBundleDocumentTypes:0:CFBundleTypeRole string Viewer' \
        -c 'Add :CFBundleDocumentTypes:0:LSHandlerRank string Owner' \
        -c 'Add :CFBundleDocumentTypes:0:LSItemContentTypes array' \
        -c 'Add :CFBundleDocumentTypes:0:LSItemContentTypes:0 string ${app.identifier}.vv' \
        [shellescape ${plist}]"
    system "${pb} -c 'Delete :UTExportedTypeDeclarations' [shellescape ${plist}]; true"
    system "${pb} \
        -c 'Add :UTExportedTypeDeclarations array' \
        -c 'Add :UTExportedTypeDeclarations:0 dict' \
        -c 'Add :UTExportedTypeDeclarations:0:UTTypeIdentifier string ${app.identifier}.vv' \
        -c 'Add :UTExportedTypeDeclarations:0:UTTypeDescription string Virt Viewer Connection File' \
        -c 'Add :UTExportedTypeDeclarations:0:UTTypeConformsTo array' \
        -c 'Add :UTExportedTypeDeclarations:0:UTTypeConformsTo:0 string public.data' \
        -c 'Add :UTExportedTypeDeclarations:0:UTTypeTagSpecification dict' \
        -c 'Add :UTExportedTypeDeclarations:0:UTTypeTagSpecification:public.filename-extension array' \
        -c 'Add :UTExportedTypeDeclarations:0:UTTypeTagSpecification:public.filename-extension:0 string vv' \
        -c 'Add :UTExportedTypeDeclarations:0:UTTypeTagSpecification:public.mime-type array' \
        -c 'Add :UTExportedTypeDeclarations:0:UTTypeTagSpecification:public.mime-type:0 string application/x-virt-viewer' \
        [shellescape ${plist}]"
}

post-activate {
    system "${prefix}/bin/update-desktop-database ${prefix}/share/applications"
    system "${prefix}/bin/gtk-update-icon-cache -f -t ${prefix}/share/icons/hicolor"
}
