# -*- 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 119754 2014-05-05 17:33:48Z pixilla@macports.org $

PortSystem          1.0
PortGroup           github 1.0
PortGroup           qt4 1.0
PortGroup           compiler_blacklist_versions 1.0

set shorthash       1a4cebf79
# set fullhash      1a4cebf795a1400987347f57faeb57cacd0805f9
set majorversion    .26
set minorversion    .1
github.setup        MythTV mythtv ${shorthash}
name                mythtv-core${majorversion}
version             0${majorversion}${minorversion}-Fixes-20140321
categories          multimedia
platforms           darwin
# i386 unsupported -- https://trac.macports.org/ticket/40337
supported_archs     x86_64
license             GPL-2
maintainers         cogeco.ca:ctreleaven openmaintainer

description         personal video recorder (PVR) and media centre system
long_description    The ultimate Digital Video Recorder and home media \
                    center hub. Think of it as a Free and Open Source alternative \
                    to Windows Media Center or Tivo.

homepage            http://www.mythtv.org/
checksums           rmd160  46c249c9746e72ffceea40310bfdce00b6491192 \
                    sha256  efe5a6d918e0be15896bc3bdd8a397f652d6aaee919381894cc6c6c7f69048be

set nick            mythtv
set mythtvhomedir   ${prefix}/var/mythtvuser
set mythtvlogdir    ${prefix}/var/log/${nick}${majorversion}
set mythtvrundir    ${prefix}/var/run/${nick}${majorversion}
set mythtvpidfile   ${mythtvrundir}/${nick}
set plistdir        ${prefix}/Library/LaunchDaemons
set plistfiles      {org.mythtv.mythbackend.plist org.mythtv.mythlogserver.plist}
set mythverstring   v0${majorversion}${minorversion}-${shorthash}-MacPorts
set mythbranch      fixes/0${majorversion}
set applescripts    {Myth_Frontend Myth_Filldatabase Myth_Setup Myth_Stop_Start}
set mysqlver        mysql5
set perlver         perl5.12
set perlbin         ${prefix}/bin/${perlver}
set perlmodver      p5.12
set pythonver       python2.6
set pythonbin       ${prefix}/bin/${pythonver}
set pymodver        py26

depends_lib         port:libdvdcss \
                    port:freetype \
                    port:lame \
                    port:x264 \
                    port:qt4-mac-${mysqlver}-plugin \
                    port:libpng \
                    port:${pymodver}-mysql \
                    port:${pymodver}-lxml \
                    port:${pymodver}-urlgrabber \
                    port:${perlmodver}-dbd-mysql \
                    port:${perlmodver}-http-request-ascgi \
                    port:${perlmodver}-lwp-useragent-determined \
                    port:${perlmodver}-io-socket-inet6 \
                    port:${perlmodver}-datemanip \
                    port:${perlmodver}-net-upnp

depends_build       port:yasm  port:pkgconfig

conflicts           mythtv-core.25 mythtv-core.27

depends_run         port:logrotate

# See http://code.mythtv.org/trac/ticket/11070
# Run-time failures experienced with certain versions of Clang.  Unable to discern cause.
# Most recent version of clang seems OK, let's try again

compiler.fallback-append apple-gcc-4.2
compiler.blacklist-append { clang <= 500.2.79 } \
    macports-clang*

pre-fetch {
    if {${os.platform} eq "darwin" && ${os.major} < 9} {
        ui_error "${name} ${version} requires Mac OS X 10.5 or greater."
        return -code error "incompatible Mac OS X version"
    }
}

# eliminate /usr/include
patchfiles          patch-configure-configincludepath.diff

#fix libmythtv linking against prior installed versions
# see mythtv-dev thread, committed to master
patchfiles-append   patch-libs_fix_linking.diff

# following three patches currently required to support MythExpress
# See tickets:
#    http://code.mythtv.org/trac/ticket/10773
#    http://code.mythtv.org/trac/ticket/10825
#    http://code.mythtv.org/trac/ticket/11032
patchfiles-append   patch-bonjour-correction.diff \
                    patch-protect-metadata-loads-from-multiple-threads.diff \
                    patch-restore-fe-netcontrol-play-resume-functionality.diff

# Clang fixes committed to 0.27-fixes but not 0.26-fixes
#  https://github.com/MythTV/mythtv/commit/f5e61804d7a8ad6afc4aa4484e2c05f24ddb396b
patchfiles-append   patch-clang_fixes.diff

# patches to support freetype 2.5.1 changes to include layout
#  http://code.mythtv.org/trac/ticket/11967
patchfiles-append   patch-freetype-2.5.1.diff

post-extract {
    file mkdir ${worksrcpath}/macports
    foreach {applescript} ${applescripts} {
        copy ${filespath}/${applescript}.applescript ${worksrcpath}/macports/${applescript}.applescript
    }
    foreach {plist} ${plistfiles} {
        copy ${filespath}/${plist} ${worksrcpath}/macports/${plist}
    }
    copy ${filespath}/logrotate.conf ${worksrcpath}/macports/logrotate.conf
    copy ${filespath}/logrotate.mythtv ${worksrcpath}/macports/logrotate.mythtv
}

post-patch {
    set sedPath ${worksrcpath}/mythtv/
    ui_info "Make Myth utils use MacPorts Perl"
    reinplace -locale C "s|check_cmd perl -e|check_cmd ${perlbin} -e|" \
        ${sedPath}configure

    reinplace -locale C "s|#!/usr/bin/env perl|#!${perlbin}|" \
        ${sedPath}programs/scripts/internetcontent/topdocumentaryfilm.pl  \
        ${sedPath}programs/scripts/internetcontent/twit.tv.pl

    reinplace -locale C "s|#!/usr/bin/perl|#!${perlbin}|" \
        ${sedPath}bindings/perl/Makefile.PL  \
        ${sedPath}bindings/perl/MythTV.pm  \
        ${sedPath}contrib/maintenance/optimize_mythdb.pl  \
        ${sedPath}contrib/user_jobs/mythlink.pl  \
        ${sedPath}programs/scripts/database/mythconverg_backup.pl \
        ${sedPath}programs/scripts/database/mythconverg_restore.pl

    reinplace -locale C "s|/usr/local/bin|${prefix}/lib/${mysqlver}/bin|"  \
        ${sedPath}programs/scripts/database/mythconverg_backup.pl \
        ${sedPath}programs/scripts/database/mythconverg_restore.pl

    ui_info "Record Myth version strings"
    reinplace -locale C "s#\${SOURCE_VERSION}#${mythverstring}#g" ${sedPath}version.sh
    reinplace -locale C "s#\${BRANCH}#${mythbranch}#g" ${sedPath}version.sh

    ui_info "Make Myth scripts use MacPorts Python  <<<<"
    # Hack to install Python bindings in ${prefix}/Library/Frameworks/Python.framework/Versions/2.6
    reinplace -locale C "s|\$(ROOT_FLAGS) \$(PREFIX_FLAGS)|\$(ROOT_FLAGS) \--prefix=\"${frameworks_dir}/Python.framework/Versions/2.6\"|" \
        ${sedPath}/bindings/python/Makefile
    reinplace -locale C "s|/usr/local|${prefix}|" ${worksrcpath}/mythtv/bindings/python/MythTV/static.py
    reinplace -locale C "s|#!python|#!${pythonbin}|" \
        ${worksrcpath}/mythtv/bindings/python/scripts/mythpython \
        ${worksrcpath}/mythtv/bindings/python/scripts/mythwikiscripts
    fs-traverse f ${sedPath}/bindings/python/ {
        if [string equal [ file extension ${f} ] ".py" ] {
            reinplace -locale C "s|^#! */usr/bin/env python\$|#!${pythonbin}|" ${f}
        }
    }
    fs-traverse f ${sedPath}/programs/scripts/ {
        if [string equal [ file extension ${f} ] ".py" ] {
            reinplace -locale C "s|^#! */usr/bin/env python\$|#!${pythonbin}|" ${f}
        }
    }
    foreach f [glob -directory ${sedPath}/programs/scripts/hardwareprofile *.py] {
    # fix even though they're currently non-functional on OS X
        reinplace -locale C "s|^#!/usr/bin/python\$|#!${pythonbin}|" ${f}
    }

    foreach {applescript} ${applescripts} {
        reinplace -locale C "s|@PREFIX@|${prefix}|g" ${worksrcpath}/macports/${applescript}.applescript
        reinplace -locale C "s|@APPLICATIONS_DIR@|${applications_dir}|" ${worksrcpath}/macports/${applescript}.applescript
        reinplace -locale C "s|@MYTHTVLOGDIR@|${mythtvlogdir}|" ${worksrcpath}/macports/${applescript}.applescript
        reinplace -locale C "s|@MYTHTVPIDFILE@|${mythtvpidfile}|" ${worksrcpath}/macports/${applescript}.applescript
    }
    foreach {plist} ${plistfiles} {
        reinplace -locale C "s|@PREFIX@|${prefix}|g" ${worksrcpath}/macports/${plist}
        reinplace -locale C "s|@MYTHTVLOGDIR@|${mythtvlogdir}|" ${worksrcpath}/macports/${plist}
        reinplace -locale C "s|@PYTHONVER@|${pythonver}|" ${worksrcpath}/macports/${plist}
        reinplace -locale C "s|@MYTHTVPIDFILE@|${mythtvpidfile}|" ${worksrcpath}/macports/${plist}
    }
    reinplace -locale C "s|@PREFIX@|${prefix}|g" ${worksrcpath}/macports/logrotate.conf
    reinplace -locale C "s|@MYTHTVLOGDIR@|${mythtvlogdir}|g" ${worksrcpath}/macports/logrotate.mythtv
    reinplace -locale C "s|xxxyyyzzz|${mythtvpidfile}|" ${worksrcpath}/mythtv/configure
#    reinplace -locale C "s|--includedir=|CC=${configure.cc} CXX=${configure.cxx} --includedir=|" \
#        ${worksrcpath}/mythtv/external/Makefile
}

################################################################################
# Let Myth set its own flags... (ala qt4-mac)                                  #
################################################################################

# except workaround broken configure handling of freetype
configure.cflags    -I${prefix}//include/freetype2
configure.cppflags
configure.cxxflags
configure.objcflags
configure.ldflags

configure.universal_cflags
configure.universal_cppflags
configure.universal_cxxflags
configure.universal_ldflags

configure.cc_archflags
configure.cxx_archflags
configure.ld_archflags

configure.dir       ${worksrcpath}/mythtv
configure.args      --compile-type=release \
                    --runprefix=${prefix} \
                    --cc=${configure.cc} \
                    --cxx=${configure.cxx} \
                    --qmake=${qt_qmake_cmd} \
                    --python=${pythonbin} \
                    --disable-ceton \
                    --disable-firewire \
                    --disable-audio-jack --disable-indev=jack \
                    --disable-libvpx --disable-libxvid \
                    --disable-qtdbus \
                    --disable-sdl \
                    --disable-xrandr \
                    --enable-libfreetype \
                    --enable-libmp3lame --enable-libx264

if {${configure.ccache} != "yes"} {
    configure.args-append --disable-ccache
}

if {${configure.distcc} != "yes"} {
    configure.args-append --disable-distcc
}

build.dir           ${worksrcpath}/mythtv

pre-build {
    ui_info "Build Myth AppleScript helper apps"
    # Compile applescrips
    foreach {applescript} ${applescripts} {
        system "osacompile -x -o ${worksrcpath}/macports/${applescript}.app ${worksrcpath}/macports/${applescript}.applescript"
    }
    # Myth custom icon for a couple of the applets
    copy -force ${configure.dir}/programs/mythfrontend/mythfrontend.icns ${worksrcpath}/macports/Myth_Frontend.app/Contents/Resources/applet.icns
    copy -force ${configure.dir}/programs/mythfrontend/mythfrontend.icns ${worksrcpath}/macports/Myth_Stop_Start.app/Contents/Resources/applet.icns
}

destroot.destdir    INSTALL_ROOT=${destroot}

post-destroot {
# make some directories myth will need
    xinstall -d -m 755 ${destroot}${mythtvhomedir}
    xinstall -d -m 777 ${destroot}${mythtvlogdir}
    xinstall -d -m 777 ${destroot}${mythtvlogdir}/old
    xinstall -d -m 755 ${destroot}${prefix}/etc/logrotate.d
    xinstall -d -m 744 ${destroot}${mythtvrundir}

    destroot.keepdirs \
        ${destroot}${mythtvhomedir} \
        ${destroot}${mythtvlogdir} \
        ${destroot}${mythtvlogdir}/old \
        ${destroot}${mythtvrundir}

# install logrotate.mythtv
    xinstall -m 400 ${worksrcpath}/macports/logrotate.mythtv ${destroot}${prefix}/etc/logrotate.d

# install the launchd plist for the backend
    ui_info "Installing startupitem/launchd plist..."
    xinstall -d -m 0755 ${destroot}${plistdir}
    foreach {plist} ${plistfiles} {
        xinstall ${worksrcpath}/macports/${plist} ${destroot}${plistdir}
    }

# install scripts we want in share/contrib
    ui_info "Installing share/$name/contrib scripts..."

    xinstall -d -m 755 ${destroot}${prefix}/share/${nick}/database
    xinstall -d -m 755 ${destroot}${prefix}/share/${nick}/contrib

    xinstall -m 755 \
        ${configure.dir}/database/mc.sql \
        ${destroot}${prefix}/share/${nick}/database
    xinstall -m 755 \
        ${configure.dir}/contrib/maintenance/optimize_mythdb.pl \
        ${configure.dir}/contrib/user_jobs/mythlink.pl \
        ${destroot}${prefix}/share/${nick}/contrib

# install some simple Applescripts to launch common myth apps
    ui_info "Installing Applescript helpers..."
    # compile the Applescripts
    xinstall -m 755 -d ${destroot}${applications_dir}/MythTV

    foreach {applescript} ${applescripts} {
        copy ${worksrcpath}/macports/${applescript}.app ${destroot}${applications_dir}/MythTV/${applescript}.app
    }

# Myth custom icon for a couple of the applets
    copy -force ${configure.dir}/programs/mythfrontend/mythfrontend.icns ${destroot}${applications_dir}/MythTV/Myth_Frontend.app/Contents/Resources/applet.icns
    copy -force ${configure.dir}/programs/mythfrontend/mythfrontend.icns ${destroot}${applications_dir}/MythTV/Myth_Stop_Start.app/Contents/Resources/applet.icns

# Fix up library entries in dylibs and executables ...
# need to loop on arch's if/when build universal ?!?
    set libdir ${prefix}/lib

    ui_info "Correcting library entries in dylibs..."

    foreach {dylib} [glob -types f -tails -directory ${destroot}${libdir} *.dylib] {
        # glob gives us both files and links to files
        if { [file type ${destroot}${libdir}/${dylib}] == "file" } {
            ui_debug "... for ${dylib}"
            system "install_name_tool -id ${libdir}/${dylib} ${destroot}${libdir}/${dylib}"

            set otool [lrange [split [exec otool -L ${destroot}${libdir}/${dylib}] \n] 1 end]

            foreach {otoolentry} ${otool} {
                # fix entries like "libmythswscale.dylib" to "${prefix}/lib/libmythswscale.dylib"
                # assume anything without a leading slash needs fixing
                set firstchar [string range [string trimleft ${otoolentry}] 0 0]
                if  { ${firstchar} != "/" }  {
                    set lib [lindex ${otoolentry} 0]
                    ui_debug "      Change ${lib}  to  ${libdir}/[file tail ${lib}]"
                    system "install_name_tool -change \
                        ${lib} \
                        ${libdir}/[file tail ${lib}] \
                        ${destroot}${libdir}/${dylib}"
                }
            }
        }
    }
    set bindir ${prefix}/bin
    ui_info "Correcting library entries in executables..."

    foreach {prog} [glob -types f -tails -directory ${destroot}${bindir} *] {
        # glob gives us files and links to files but should be no links in bin dir
        ui_debug "... for ${prog}"

        set otool [lrange [split [exec otool -L ${destroot}${bindir}/${prog}] \n] 1 end]

        foreach {otoolentry} ${otool} {
            # fix entries like "libmythswscale.dylib" to "${prefix}/lib/libmythswscale.dylib"
            # assume anything without a leading slash needs fixing
            set firstchar [string range [string trimleft ${otoolentry}] 0 0]
            if  { ${firstchar} != "/" }  {
                set lib [lindex ${otoolentry} 0]
                ui_debug "      Change ${lib} to ${libdir}/[file tail ${lib}]"
                system "install_name_tool -change \
                    ${lib} \
                    ${libdir}/[file tail ${lib}] \
                    ${destroot}${bindir}/${prog}"
            }
        }
    }

# fix lib entries in filters
    set fltdir ${prefix}/lib/mythtv/filters
    set liblist [glob -types f -tails -directory ${destroot}${libdir} -- *.dylib]
    ui_info "Correcting library entries in plugins..."

    foreach {flt} [glob -types f -tails -directory ${destroot}${fltdir} *] {
        # glob gives us files and links to files but should be no links in filters dir
        ui_debug "... for ${flt}"

        set otool [lrange [split [exec otool -L ${destroot}${fltdir}/${flt}] \n] 1 end]

        foreach {otoolentry} ${otool} {
            # fix entries like "libmythswscale.dylib" to "${prefix}/lib/libmythswscale.dylib"
            # assume anything without a leading slash needs fixing
            set firstchar [string range [string trimleft ${otoolentry}] 0 0]
            if  { ${firstchar} != "/" }  {
                set lib [lindex ${otoolentry} 0]
                if { [ lsearch $liblist ${lib} ] > 0 } {
                    set goodprefix ${libdir}
                } else {
                    set goodprefix ${fltdir}
                }
                ui_debug "      Change ${lib} to ${goodprefix}/[file tail ${lib}]"
                system "install_name_tool -change \
                    ${lib} \
                    ${goodprefix}/[file tail ${lib}] \
                    ${destroot}${fltdir}/${flt}"
            }
        }
    }
}

universal_variant           no

post-activate {
    # make logrotate ready to go
    if {![file exists ${prefix}/etc/logrotate.conf]} {
        file copy ${destroot}logrotate.conf ${prefix}/etc/logrotate.conf
    }
    # delete leftover files, if any
    foreach {plist} ${plistfiles} {
        if [file exists /Library/LaunchDaemons/${plist}] {
            file delete -force /Library/LaunchDaemons/${plist}
        }
    }
    # The startupitem.install keyword does not exist in MacPorts < 2.1.
    if {![info exists startupitem.install]} {
        set startupitem.install yes
    }
    # If "startupitem.install" is set to "no" in macports.conf then do not link.
    if {${startupitem.install} != "no"} {
        foreach {plist} ${plistfiles} {
            ln -s ${plistdir}/${plist} /Library/LaunchDaemons
        }
    }
}

pre-deactivate {
    foreach {plist} ${plistfiles} {
        file delete -force ${plistdir}/${plist}
    }
}

notes "############################################################################
#
# See http://www.mythtv.org/wiki/Myth_for_Mac_with_MacPorts for information
# essential to finishing the installation of MythTV!
#
# NB -
# For troubleshooting, all Myth-related logs are stored in
# ${mythtvlogdir}
#
############################################################################"

livecheck.version       ${majorversion}${minorversion}
livecheck.regex         "archive/v(0${majorversion}\[\\.\\d\]?)${extract.suffix}"
