# -*- 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           github 1.0
PortGroup           active_variants 1.1
PortGroup           app 1.1
PortGroup           qt6 1.0

github.setup        XiaoYouChR Ghost-Downloader-3 4.5.11 v
github.tarball_from archive
revision            0
name                [string tolower [join [lrange [split ${github.project} -] 0 1] -]]
categories          net python
homepage            https://gd.xychr.com
license             GPL-3
maintainers         {i0ntempest @i0ntempest} openmaintainer

description         The only downloader you need
long_description    ${name} aims to be [string tolower ${description}]. It employs multithreaded\
                    and intelligent load balancing, supports HTTP(S), QUIC, BitTorrent, eD2k, M3U8,\
                    common video sites, media sniffing, browser integration, and more.

checksums           rmd160  979b8fba5a048cf82043278dfd74bc5a83ae7d89 \
                    sha256  c8f9613daf91bb835fde8e053db0357152bea53abeb957ff889e2176a68fd3a3 \
                    size    13113178

set python_version  314
set python_branch   [string index ${python_version} 0].[string range ${python_version} 1 end]

depends_build-append \
                    port:py${python_version}-nuitka

# aioftp[socks] (1 extra dep)
# qrcode[png] (extra deps added in its portfile)
depends_lib-append  port:libtorrent-rasterbar \
                    port:python${python_version} \
                    port:py${python_version}-pyobjc \
                    port:py${python_version}-desktop-notifier \
                    port:py${python_version}-loguru \
                    port:py${python_version}-wreq \
                    port:py${python_version}-websockets \
                    port:py${python_version}-pyside6 \
                    port:py${python_version}-pyside6-fluent-widgets \
                    port:py${python_version}-qrcode \
                    port:py${python_version}-uvloop \
                    port:py${python_version}-aioftp \
                    port:py${python_version}-siosocks \
                    port:py${python_version}-m3u8 \
                    port:py${python_version}-mpegdash

depends_run-append  port:kelpie

qt6.depends_lib     qttranslations

require_active_variants \
                    port:libtorrent-rasterbar python${python_version}

# https://github.com/XiaoYouChR/Ghost-Downloader-3/pull/928 - disable auto update
patchfiles-append   patch-928.diff
# https://github.com/XiaoYouChR/Ghost-Downloader-3/pull/934 - threads slider fix and single threaded mode
patchfiles-append   patch-934.diff
# https://github.com/XiaoYouChR/Ghost-Downloader-3/pull/933 - bilibili multi-file task naming
patchfiles-append   patch-933.diff
patch.args          -p1

post-patch {
    # We don't compile in standalone mode so sys.executable is the interpreter
    reinplace "s|sys.executable|sys.argv\[0\]|g" ${worksrcpath}/app/config/paths.py
    # change default kelpie directory
    reinplace "s|{APP_DATA_DIR}/kelpie|${prefix}/libexec/kelpie|g" ${worksrcpath}/features/ed2k_pack/config.py
    # change hardcoded prefix
    reinplace "s|/usr/local|${prefix}|g" ${worksrcpath}/app/platform/cli_install.py
}

# Project does not have a typical Python project structure (pyproject.toml not usable for installation).
# deploy.py compiles standalone bundle and packs everything with nuitka into one app bundle - 
# avoid that, make our own bundle. We compile the main script and the `app` package only.
use_configure       no
post-configure {
    # refresh translation
    system -W ${worksrcpath} "${prefix}/bin/python${python_branch} scripts/sync_i18n_res.py"
}

build.cmd           ${prefix}/bin/python${python_branch} -m nuitka
build.target        ${github.project}.py
build.args          --verbose \
                    --plugin-enable=pyside6 \
                    --include-package=app \
                    --static-libpython=no \
                    --disable-ccache \
                    --macos-app-macos-min-version=${macosx_deployment_target}

app.executable      ${worksrcpath}/${github.project}.bin
app.icon            ${worksrcpath}/app/assets/logo.icns
app.name            {*}[join [lrange [split ${github.project} -] 0 1] " "]
app.identifier      io.github.[string tolower ${github.author}].[join [lrange [split ${github.project} -] 0 1] ""]
app.retina          yes
app.sign            yes
app.signing_args    --deep
app.manual_post_destroot \
                    yes

set dest_app ${destroot}${applications_dir}/${app.name}.app
set dest_app_bin_dir ${dest_app}/Contents/MacOS/
set dest_app_res_dir ${dest_app}/Contents/Resources/
set dest_app_info_plist ${dest_app}/Contents/Info.plist
# see MACOS_DOCUMENT_TYPES in scripts/deploy.py for supported file types
set document_types [list \
    [list "Torrent File"   "torrent.icns" "Viewer" "Alternate" [list "torrent"]] \
    [list "M3U8 Playlist"  "m3u8.icns"    "Viewer" "Alternate" [list "m3u8" "m3u"]] \
    [list "DASH List"      "m3u8.icns"    "Viewer" "Alternate" [list "mpd"]] \
]
# see scripts/deploy.py for supported URL schemes
set url_types [list \
    [list "${app.identifier}" [list "ghostdownloader" "magnet" "ed2k" "ftp" "ftps" "thunder" "flashget" "qqdl"]] \
]

destroot {
    copy ${worksrcpath}/features/ ${dest_app_bin_dir}
    # --include-data-files ignored in non-standalone build, copy resource file manually
    xinstall -d ${dest_app_bin_dir}/app/assets/
    xinstall -m 0644 ${worksrcpath}/app/assets/resources.rcc ${dest_app_bin_dir}/app/assets/
    # see EXCLUDED_PACKS in deploy.py
    set feature_pack_blacklist {jack_yao}
    foreach pack ${feature_pack_blacklist} {
        delete ${dest_app_bin_dir}/features/${pack}
    }
    set file_icons_dir ${worksrcpath}/app/assets/file_icons
    set copied_icons [list]
    foreach document_type ${document_types} {
        lassign ${document_type} type_name icon_file type_role handler_rank extensions
        if {[lsearch -exact ${copied_icons} ${icon_file}] < 0} {
            xinstall -m 0644 \
                ${file_icons_dir}/${icon_file} \
                ${dest_app_res_dir}/${icon_file}
            lappend copied_icons ${icon_file}
        }
    }

    # command-line interface
    ln -s "${applications_dir}/${app.name}.app/Contents/MacOS/${app.name}" ${destroot}${prefix}/bin/ghd
}

post-destroot {
    app::post_destroot

    set plistbuddy /usr/libexec/PlistBuddy

    # file associations
    exec ${plistbuddy} -c "Add :CFBundleDocumentTypes array" ${dest_app_info_plist}
    set i 0
    foreach document_type ${document_types} {
        lassign ${document_type} type_name icon_file type_role handler_rank extensions

        exec ${plistbuddy} -c "Add :CFBundleDocumentTypes:${i} dict" ${dest_app_info_plist}
        exec ${plistbuddy} -c "Add :CFBundleDocumentTypes:${i}:CFBundleTypeExtensions array" ${dest_app_info_plist}

        set j 0
        foreach ext ${extensions} {
            exec ${plistbuddy} -c "Add :CFBundleDocumentTypes:${i}:CFBundleTypeExtensions:${j} string ${ext}" ${dest_app_info_plist}
            incr j
        }

        exec ${plistbuddy} -c "Add :CFBundleDocumentTypes:${i}:CFBundleTypeIconFile string ${icon_file}" ${dest_app_info_plist}
        exec ${plistbuddy} -c "Add :CFBundleDocumentTypes:${i}:CFBundleTypeName string ${type_name}" ${dest_app_info_plist}
        exec ${plistbuddy} -c "Add :CFBundleDocumentTypes:${i}:CFBundleTypeRole string ${type_role}" ${dest_app_info_plist}
        exec ${plistbuddy} -c "Add :CFBundleDocumentTypes:${i}:LSHandlerRank string ${handler_rank}" ${dest_app_info_plist}

        incr i
    }

    # URL scheme handlers
    exec ${plistbuddy} -c "Add :CFBundleURLTypes array" ${dest_app_info_plist}
    set i 0
    foreach url_type ${url_types} {
        lassign ${url_type} url_name url_schemes

        exec ${plistbuddy} -c "Add :CFBundleURLTypes:${i} dict" ${dest_app_info_plist}
        exec ${plistbuddy} -c "Add :CFBundleURLTypes:${i}:CFBundleURLName string ${url_name}" ${dest_app_info_plist}
        exec ${plistbuddy} -c "Add :CFBundleURLTypes:${i}:CFBundleURLSchemes array" ${dest_app_info_plist}

        set j 0
        foreach scheme ${url_schemes} {
            exec ${plistbuddy} -c "Add :CFBundleURLTypes:${i}:CFBundleURLSchemes:${j} string ${scheme}" ${dest_app_info_plist}
            incr j
        }

        incr i
    }

    # deployment target
    exec ${plistbuddy} -c "Add :LSMinimumSystemVersion string ${macosx_deployment_target}" ${dest_app_info_plist}

    # Downloads folder access request prompt
    set dl_access_request "${app.name} needs to access your Downloads folder to manage downloads."
    exec ${plistbuddy} -c "Add :NSDownloadsFolderUsageDescription string ${dl_access_request}" ${dest_app_info_plist}

    # copyright string
    set copyright "Copyright(C) [clock format ${source_date_epoch} -format %Y] ${github.author}, MacPorts port by [lindex [split [lindex ${maintainers} 0] " "] 0]"
    exec ${plistbuddy} -c "Add :NSHumanReadableCopyright string ${copyright}" ${dest_app_info_plist}

    # no auto update marker
    set fp [open ${dest_app_bin_dir}/gd_no_auto_update w]
    puts -nonewline ${fp} "MacPorts"
    close ${fp}

    app::sign
}

variant media description {enable and install dependencies for media downloading and muxing support} {
    depends_run-append \
                    port:ffmpeg \
                    port:n-m3u8dl-re \
                    port:yt-dlp \
                    port:quickjs-ng

    app.signing_args-append \
                    --force

    # declare in global namespace
    set ::youtube_runtime_folder \
                    "deps/YtDlp/"

    post-patch {
        # change default ffmpeg directory
        reinplace "s|{APP_DATA_DIR}/FFmpeg|${prefix}/bin|g" ${worksrcpath}/features/ffmpeg_pack/config.py
        # change default n-m3u8dl-re directory
        reinplace "s|{APP_DATA_DIR}/M3U8DL|${prefix}/bin|g" ${worksrcpath}/features/m3u8_pack/config.py
        # change default youtube support runtime (yt-dlp source & qjs binary) directory
        reinplace "s|f\"{APP_DATA_DIR}/YtDlp\"|str(Path(sys.argv\[0\]).resolve().parent / \"${youtube_runtime_folder}\")|g" ${worksrcpath}/features/yt_dlp_pack/config.py
    }

    post-destroot {
        # youtube support runtime symlinks
        xinstall -d ${dest_app_bin_dir}/${youtube_runtime_folder}
        ln -s ${prefix}/bin/qjs ${dest_app_bin_dir}/${youtube_runtime_folder}
        ln -s ${prefix}/Library/Frameworks/Python.framework/Versions/${python_branch}/lib/python${python_branch}/site-packages/yt_dlp/ ${dest_app_bin_dir}/${youtube_runtime_folder}
        app::sign
    }
}

variant debug description {Enable runtime checks and preserve debugging artifacts} {
    patchfiles-append patch-debug-logging.diff

    build.args-append \
                    --debug \
                    --no-debug-c-warnings \
                    --no-debug-immortal-assumptions \
                    --lto=no \
                    --report=${worksrcpath}/compilation-report.xml

    post-build {
        system -W ${worksrcpath} \
            "/usr/bin/xcrun dsymutil [shellescape ${app.executable}] \
            -o [shellescape ${worksrcpath}/${name}.dSYM]"
    }

    post-destroot {
        set debug_dir ${prefix}/libexec/${name}/debug/${version}_${revision}
        xinstall -d ${destroot}${debug_dir}/sources
        copy ${worksrcpath}/${name}.dSYM ${destroot}${debug_dir}
        xinstall -m 0755 ${app.executable} ${destroot}${debug_dir}/${github.project}.bin
        xinstall -m 0644 ${worksrcpath}/compilation-report.xml ${destroot}${debug_dir}
        foreach source [glob -nocomplain \
                -directory ${worksrcpath}/${github.project}.build *.c *.h] {
            xinstall -m 0644 ${source} ${destroot}${debug_dir}/sources
        }

        xinstall -m 0755 ${filespath}/ghost-downloader-debug \
            ${destroot}${prefix}/bin/ghost-downloader-debug
        reinplace "s|@APP_EXECUTABLE@|${applications_dir}/${app.name}.app/Contents/MacOS/${app.name}|g" \
            ${destroot}${prefix}/bin/ghost-downloader-debug
        reinplace "s|@DEBUG_DIR@|${debug_dir}|g" \
            ${destroot}${prefix}/bin/ghost-downloader-debug
        reinplace "s|@BUILD_DIR@|${worksrcpath}/${github.project}.build|g" \
            ${destroot}${prefix}/bin/ghost-downloader-debug
    }

    notes-append "The ghost-downloader-debug command launches the GUI under LLDB.\n\
        Quit any existing instance first and keep the terminal open.\n\
        Add --core to save a full core dump on a crash; this can take minutes,\n\
        use gigabytes, and include credentials.\n\
        Diagnostics: ~/Library/Logs/GhostDownloader/Debug\n\
        The matching executable, debug symbols, generated C sources, and compilation\n\
        report are installed in ${prefix}/libexec/${name}/debug/${version}_${revision}.\n\
        Archive these before upgrading. Apple's Command Line Tools or Xcode\n\
        are required to run the debugger."
}

default_variants    +media
