192b42cb3SPatrick Williams#
292b42cb3SPatrick Williams# Copyright OpenEmbedded Contributors
392b42cb3SPatrick Williams#
492b42cb3SPatrick Williams# SPDX-License-Identifier: MIT
592b42cb3SPatrick Williams#
692b42cb3SPatrick Williams
792b42cb3SPatrick Williamsinherit package
892b42cb3SPatrick Williams
992b42cb3SPatrick WilliamsIMAGE_PKGTYPE ?= "ipk"
1092b42cb3SPatrick Williams
1192b42cb3SPatrick WilliamsIPKGCONF_TARGET = "${WORKDIR}/opkg.conf"
1292b42cb3SPatrick WilliamsIPKGCONF_SDK =  "${WORKDIR}/opkg-sdk.conf"
1392b42cb3SPatrick WilliamsIPKGCONF_SDK_TARGET = "${WORKDIR}/opkg-sdk-target.conf"
1492b42cb3SPatrick Williams
1592b42cb3SPatrick WilliamsPKGWRITEDIRIPK = "${WORKDIR}/deploy-ipks"
1692b42cb3SPatrick Williams
1792b42cb3SPatrick Williams# Program to be used to build opkg packages
1892b42cb3SPatrick WilliamsOPKGBUILDCMD ??= 'opkg-build -Z xz -a "${XZ_DEFAULTS}"'
1992b42cb3SPatrick Williams
2092b42cb3SPatrick WilliamsOPKG_ARGS += "--force_postinstall --prefer-arch-to-version"
2192b42cb3SPatrick WilliamsOPKG_ARGS += "${@['', '--no-install-recommends'][d.getVar("NO_RECOMMENDATIONS") == "1"]}"
2292b42cb3SPatrick WilliamsOPKG_ARGS += "${@['', '--add-exclude ' + ' --add-exclude '.join((d.getVar('PACKAGE_EXCLUDE') or "").split())][(d.getVar("PACKAGE_EXCLUDE") or "").strip() != ""]}"
2392b42cb3SPatrick Williams
2492b42cb3SPatrick WilliamsOPKGLIBDIR ??= "${localstatedir}/lib"
2592b42cb3SPatrick Williams
2692b42cb3SPatrick Williamspython do_package_ipk () {
2792b42cb3SPatrick Williams    workdir = d.getVar('WORKDIR')
2892b42cb3SPatrick Williams    outdir = d.getVar('PKGWRITEDIRIPK')
2992b42cb3SPatrick Williams    tmpdir = d.getVar('TMPDIR')
3092b42cb3SPatrick Williams    pkgdest = d.getVar('PKGDEST')
3192b42cb3SPatrick Williams    if not workdir or not outdir or not tmpdir:
3292b42cb3SPatrick Williams        bb.error("Variables incorrectly set, unable to package")
3392b42cb3SPatrick Williams        return
3492b42cb3SPatrick Williams
3592b42cb3SPatrick Williams    packages = d.getVar('PACKAGES')
3692b42cb3SPatrick Williams    if not packages or packages == '':
3792b42cb3SPatrick Williams        bb.debug(1, "No packages; nothing to do")
3892b42cb3SPatrick Williams        return
3992b42cb3SPatrick Williams
4092b42cb3SPatrick Williams    # We're about to add new packages so the index needs to be checked
4192b42cb3SPatrick Williams    # so remove the appropriate stamp file.
4292b42cb3SPatrick Williams    if os.access(os.path.join(tmpdir, "stamps", "IPK_PACKAGE_INDEX_CLEAN"), os.R_OK):
4392b42cb3SPatrick Williams        os.unlink(os.path.join(tmpdir, "stamps", "IPK_PACKAGE_INDEX_CLEAN"))
4492b42cb3SPatrick Williams
4592b42cb3SPatrick Williams    oe.utils.multiprocess_launch(ipk_write_pkg, packages.split(), d, extraargs=(d,))
4692b42cb3SPatrick Williams}
4792b42cb3SPatrick Williamsdo_package_ipk[vardeps] += "ipk_write_pkg"
4892b42cb3SPatrick Williamsdo_package_ipk[vardepsexclude] = "BB_NUMBER_THREADS"
4992b42cb3SPatrick Williams
5092b42cb3SPatrick Williamsdef ipk_write_pkg(pkg, d):
5192b42cb3SPatrick Williams    import re, copy
5292b42cb3SPatrick Williams    import subprocess
5392b42cb3SPatrick Williams    import textwrap
5492b42cb3SPatrick Williams    import collections
5592b42cb3SPatrick Williams    import glob
5692b42cb3SPatrick Williams
5792b42cb3SPatrick Williams    def cleanupcontrol(root):
5892b42cb3SPatrick Williams        for p in ['CONTROL', 'DEBIAN']:
5992b42cb3SPatrick Williams            p = os.path.join(root, p)
6092b42cb3SPatrick Williams            if os.path.exists(p):
6192b42cb3SPatrick Williams                bb.utils.prunedir(p)
6292b42cb3SPatrick Williams
6392b42cb3SPatrick Williams    outdir = d.getVar('PKGWRITEDIRIPK')
6492b42cb3SPatrick Williams    pkgdest = d.getVar('PKGDEST')
6592b42cb3SPatrick Williams    recipesource = os.path.basename(d.getVar('FILE'))
6692b42cb3SPatrick Williams
6792b42cb3SPatrick Williams    localdata = bb.data.createCopy(d)
6892b42cb3SPatrick Williams    root = "%s/%s" % (pkgdest, pkg)
6992b42cb3SPatrick Williams
7092b42cb3SPatrick Williams    lf = bb.utils.lockfile(root + ".lock")
7192b42cb3SPatrick Williams    try:
7292b42cb3SPatrick Williams        localdata.setVar('ROOT', '')
7392b42cb3SPatrick Williams        localdata.setVar('ROOT_%s' % pkg, root)
7492b42cb3SPatrick Williams        pkgname = localdata.getVar('PKG:%s' % pkg)
7592b42cb3SPatrick Williams        if not pkgname:
7692b42cb3SPatrick Williams            pkgname = pkg
7792b42cb3SPatrick Williams        localdata.setVar('PKG', pkgname)
7892b42cb3SPatrick Williams
7992b42cb3SPatrick Williams        localdata.setVar('OVERRIDES', d.getVar("OVERRIDES", False) + ":" + pkg)
8092b42cb3SPatrick Williams
8192b42cb3SPatrick Williams        basedir = os.path.join(os.path.dirname(root))
8292b42cb3SPatrick Williams        arch = localdata.getVar('PACKAGE_ARCH')
8392b42cb3SPatrick Williams
8492b42cb3SPatrick Williams        if localdata.getVar('IPK_HIERARCHICAL_FEED', False) == "1":
8592b42cb3SPatrick Williams            # Spread packages across subdirectories so each isn't too crowded
8692b42cb3SPatrick Williams            if pkgname.startswith('lib'):
8792b42cb3SPatrick Williams                pkg_prefix = 'lib' + pkgname[3]
8892b42cb3SPatrick Williams            else:
8992b42cb3SPatrick Williams                pkg_prefix = pkgname[0]
9092b42cb3SPatrick Williams
9192b42cb3SPatrick Williams            # Keep -dbg, -dev, -doc, -staticdev, -locale and -locale-* packages
9292b42cb3SPatrick Williams            # together. These package suffixes are taken from the definitions of
9392b42cb3SPatrick Williams            # PACKAGES and PACKAGES_DYNAMIC in meta/conf/bitbake.conf
9492b42cb3SPatrick Williams            if pkgname[-4:] in ('-dbg', '-dev', '-doc'):
9592b42cb3SPatrick Williams                pkg_subdir = pkgname[:-4]
9692b42cb3SPatrick Williams            elif pkgname.endswith('-staticdev'):
9792b42cb3SPatrick Williams                pkg_subdir = pkgname[:-10]
9892b42cb3SPatrick Williams            elif pkgname.endswith('-locale'):
9992b42cb3SPatrick Williams                pkg_subdir = pkgname[:-7]
10092b42cb3SPatrick Williams            elif '-locale-' in pkgname:
10192b42cb3SPatrick Williams                pkg_subdir = pkgname[:pkgname.find('-locale-')]
10292b42cb3SPatrick Williams            else:
10392b42cb3SPatrick Williams                pkg_subdir = pkgname
10492b42cb3SPatrick Williams
10592b42cb3SPatrick Williams            pkgoutdir = "%s/%s/%s/%s" % (outdir, arch, pkg_prefix, pkg_subdir)
10692b42cb3SPatrick Williams        else:
10792b42cb3SPatrick Williams            pkgoutdir = "%s/%s" % (outdir, arch)
10892b42cb3SPatrick Williams
10992b42cb3SPatrick Williams        bb.utils.mkdirhier(pkgoutdir)
11092b42cb3SPatrick Williams        os.chdir(root)
11192b42cb3SPatrick Williams        cleanupcontrol(root)
11292b42cb3SPatrick Williams        g = glob.glob('*')
11392b42cb3SPatrick Williams        if not g and localdata.getVar('ALLOW_EMPTY', False) != "1":
11492b42cb3SPatrick Williams            bb.note("Not creating empty archive for %s-%s-%s" % (pkg, localdata.getVar('PKGV'), localdata.getVar('PKGR')))
11592b42cb3SPatrick Williams            return
11692b42cb3SPatrick Williams
11792b42cb3SPatrick Williams        controldir = os.path.join(root, 'CONTROL')
11892b42cb3SPatrick Williams        bb.utils.mkdirhier(controldir)
11992b42cb3SPatrick Williams        ctrlfile = open(os.path.join(controldir, 'control'), 'w')
12092b42cb3SPatrick Williams
12192b42cb3SPatrick Williams        fields = []
12292b42cb3SPatrick Williams        pe = d.getVar('PKGE')
12392b42cb3SPatrick Williams        if pe and int(pe) > 0:
12492b42cb3SPatrick Williams            fields.append(["Version: %s:%s-%s\n", ['PKGE', 'PKGV', 'PKGR']])
12592b42cb3SPatrick Williams        else:
12692b42cb3SPatrick Williams            fields.append(["Version: %s-%s\n", ['PKGV', 'PKGR']])
12792b42cb3SPatrick Williams        fields.append(["Description: %s\n", ['DESCRIPTION']])
12892b42cb3SPatrick Williams        fields.append(["Section: %s\n", ['SECTION']])
12992b42cb3SPatrick Williams        fields.append(["Priority: %s\n", ['PRIORITY']])
13092b42cb3SPatrick Williams        fields.append(["Maintainer: %s\n", ['MAINTAINER']])
13192b42cb3SPatrick Williams        fields.append(["License: %s\n", ['LICENSE']])
13292b42cb3SPatrick Williams        fields.append(["Architecture: %s\n", ['PACKAGE_ARCH']])
13392b42cb3SPatrick Williams        fields.append(["OE: %s\n", ['PN']])
13492b42cb3SPatrick Williams        if d.getVar('HOMEPAGE'):
13592b42cb3SPatrick Williams            fields.append(["Homepage: %s\n", ['HOMEPAGE']])
13692b42cb3SPatrick Williams
13792b42cb3SPatrick Williams        def pullData(l, d):
13892b42cb3SPatrick Williams            l2 = []
13992b42cb3SPatrick Williams            for i in l:
14092b42cb3SPatrick Williams                l2.append(d.getVar(i))
14192b42cb3SPatrick Williams            return l2
14292b42cb3SPatrick Williams
14392b42cb3SPatrick Williams        ctrlfile.write("Package: %s\n" % pkgname)
14492b42cb3SPatrick Williams        # check for required fields
14592b42cb3SPatrick Williams        for (c, fs) in fields:
14692b42cb3SPatrick Williams            for f in fs:
14792b42cb3SPatrick Williams                if localdata.getVar(f, False) is None:
14892b42cb3SPatrick Williams                    raise KeyError(f)
14992b42cb3SPatrick Williams            # Special behavior for description...
15092b42cb3SPatrick Williams            if 'DESCRIPTION' in fs:
15192b42cb3SPatrick Williams                summary = localdata.getVar('SUMMARY') or localdata.getVar('DESCRIPTION') or "."
15292b42cb3SPatrick Williams                ctrlfile.write('Description: %s\n' % summary)
15392b42cb3SPatrick Williams                description = localdata.getVar('DESCRIPTION') or "."
15492b42cb3SPatrick Williams                description = textwrap.dedent(description).strip()
15592b42cb3SPatrick Williams                if '\\n' in description:
15692b42cb3SPatrick Williams                    # Manually indent: multiline description includes a leading space
15792b42cb3SPatrick Williams                    for t in description.split('\\n'):
15892b42cb3SPatrick Williams                        ctrlfile.write(' %s\n' % (t.strip() or ' .'))
15992b42cb3SPatrick Williams                else:
16092b42cb3SPatrick Williams                    # Auto indent
16192b42cb3SPatrick Williams                    ctrlfile.write('%s\n' % textwrap.fill(description, width=74, initial_indent=' ', subsequent_indent=' '))
16292b42cb3SPatrick Williams            else:
16392b42cb3SPatrick Williams                ctrlfile.write(c % tuple(pullData(fs, localdata)))
16492b42cb3SPatrick Williams
165*517393d9SAndrew Geissler        custom_fields_chunk = oe.packagedata.get_package_additional_metadata("ipk", localdata)
16692b42cb3SPatrick Williams        if custom_fields_chunk is not None:
16792b42cb3SPatrick Williams            ctrlfile.write(custom_fields_chunk)
16892b42cb3SPatrick Williams            ctrlfile.write("\n")
16992b42cb3SPatrick Williams
170*517393d9SAndrew Geissler        oe.packagedata.mapping_rename_hook(localdata)
17192b42cb3SPatrick Williams
17292b42cb3SPatrick Williams        def debian_cmp_remap(var):
17392b42cb3SPatrick Williams            # In debian '>' and '<' do not mean what it appears they mean
17492b42cb3SPatrick Williams            #   '<' = less or equal
17592b42cb3SPatrick Williams            #   '>' = greater or equal
17692b42cb3SPatrick Williams            # adjust these to the '<<' and '>>' equivalents
17792b42cb3SPatrick Williams            # Also, "=" specifiers only work if they have the PR in, so 1.2.3 != 1.2.3-r0
17892b42cb3SPatrick Williams            # so to avoid issues, map this to ">= 1.2.3 << 1.2.3.0"
17992b42cb3SPatrick Williams            for dep in var:
18092b42cb3SPatrick Williams                for i, v in enumerate(var[dep]):
18192b42cb3SPatrick Williams                    if (v or "").startswith("< "):
18292b42cb3SPatrick Williams                        var[dep][i] = var[dep][i].replace("< ", "<< ")
18392b42cb3SPatrick Williams                    elif (v or "").startswith("> "):
18492b42cb3SPatrick Williams                        var[dep][i] = var[dep][i].replace("> ", ">> ")
18592b42cb3SPatrick Williams                    elif (v or "").startswith("= ") and "-r" not in v:
18692b42cb3SPatrick Williams                        ver = var[dep][i].replace("= ", "")
18792b42cb3SPatrick Williams                        var[dep][i] = var[dep][i].replace("= ", ">= ")
18892b42cb3SPatrick Williams                        var[dep].append("<< " + ver + ".0")
18992b42cb3SPatrick Williams
19092b42cb3SPatrick Williams        rdepends = bb.utils.explode_dep_versions2(localdata.getVar("RDEPENDS") or "")
19192b42cb3SPatrick Williams        debian_cmp_remap(rdepends)
19292b42cb3SPatrick Williams        rrecommends = bb.utils.explode_dep_versions2(localdata.getVar("RRECOMMENDS") or "")
19392b42cb3SPatrick Williams        debian_cmp_remap(rrecommends)
19492b42cb3SPatrick Williams        rsuggests = bb.utils.explode_dep_versions2(localdata.getVar("RSUGGESTS") or "")
19592b42cb3SPatrick Williams        debian_cmp_remap(rsuggests)
19692b42cb3SPatrick Williams        # Deliberately drop version information here, not wanted/supported by ipk
19792b42cb3SPatrick Williams        rprovides = dict.fromkeys(bb.utils.explode_dep_versions2(localdata.getVar("RPROVIDES") or ""), [])
19892b42cb3SPatrick Williams        rprovides = collections.OrderedDict(sorted(rprovides.items(), key=lambda x: x[0]))
19992b42cb3SPatrick Williams        debian_cmp_remap(rprovides)
20092b42cb3SPatrick Williams        rreplaces = bb.utils.explode_dep_versions2(localdata.getVar("RREPLACES") or "")
20192b42cb3SPatrick Williams        debian_cmp_remap(rreplaces)
20292b42cb3SPatrick Williams        rconflicts = bb.utils.explode_dep_versions2(localdata.getVar("RCONFLICTS") or "")
20392b42cb3SPatrick Williams        debian_cmp_remap(rconflicts)
20492b42cb3SPatrick Williams
20592b42cb3SPatrick Williams        if rdepends:
20692b42cb3SPatrick Williams            ctrlfile.write("Depends: %s\n" % bb.utils.join_deps(rdepends))
20792b42cb3SPatrick Williams        if rsuggests:
20892b42cb3SPatrick Williams            ctrlfile.write("Suggests: %s\n" % bb.utils.join_deps(rsuggests))
20992b42cb3SPatrick Williams        if rrecommends:
21092b42cb3SPatrick Williams            ctrlfile.write("Recommends: %s\n" % bb.utils.join_deps(rrecommends))
21192b42cb3SPatrick Williams        if rprovides:
21292b42cb3SPatrick Williams            ctrlfile.write("Provides: %s\n" % bb.utils.join_deps(rprovides))
21392b42cb3SPatrick Williams        if rreplaces:
21492b42cb3SPatrick Williams            ctrlfile.write("Replaces: %s\n" % bb.utils.join_deps(rreplaces))
21592b42cb3SPatrick Williams        if rconflicts:
21692b42cb3SPatrick Williams            ctrlfile.write("Conflicts: %s\n" % bb.utils.join_deps(rconflicts))
21792b42cb3SPatrick Williams        ctrlfile.write("Source: %s\n" % recipesource)
21892b42cb3SPatrick Williams        ctrlfile.close()
21992b42cb3SPatrick Williams
22092b42cb3SPatrick Williams        for script in ["preinst", "postinst", "prerm", "postrm"]:
22192b42cb3SPatrick Williams            scriptvar = localdata.getVar('pkg_%s' % script)
22292b42cb3SPatrick Williams            if not scriptvar:
22392b42cb3SPatrick Williams                continue
22492b42cb3SPatrick Williams            scriptfile = open(os.path.join(controldir, script), 'w')
22592b42cb3SPatrick Williams            scriptfile.write(scriptvar)
22692b42cb3SPatrick Williams            scriptfile.close()
22792b42cb3SPatrick Williams            os.chmod(os.path.join(controldir, script), 0o755)
22892b42cb3SPatrick Williams
229*517393d9SAndrew Geissler        conffiles_str = ' '.join(oe.package.get_conffiles(pkg, d))
23092b42cb3SPatrick Williams        if conffiles_str:
23192b42cb3SPatrick Williams            conffiles = open(os.path.join(controldir, 'conffiles'), 'w')
23292b42cb3SPatrick Williams            for f in conffiles_str.split():
23392b42cb3SPatrick Williams                if os.path.exists(oe.path.join(root, f)):
23492b42cb3SPatrick Williams                    conffiles.write('%s\n' % f)
23592b42cb3SPatrick Williams            conffiles.close()
23692b42cb3SPatrick Williams
23792b42cb3SPatrick Williams        os.chdir(basedir)
23892b42cb3SPatrick Williams        subprocess.check_output("PATH=\"%s\" %s %s %s" % (localdata.getVar("PATH"),
23992b42cb3SPatrick Williams                                                          d.getVar("OPKGBUILDCMD"), pkg, pkgoutdir),
24092b42cb3SPatrick Williams                                stderr=subprocess.STDOUT,
24192b42cb3SPatrick Williams                                shell=True)
24292b42cb3SPatrick Williams
24392b42cb3SPatrick Williams        if d.getVar('IPK_SIGN_PACKAGES') == '1':
24492b42cb3SPatrick Williams            ipkver = "%s-%s" % (localdata.getVar('PKGV'), localdata.getVar('PKGR'))
24592b42cb3SPatrick Williams            ipk_to_sign = "%s/%s_%s_%s.ipk" % (pkgoutdir, pkgname, ipkver, localdata.getVar('PACKAGE_ARCH'))
24692b42cb3SPatrick Williams            sign_ipk(d, ipk_to_sign)
24792b42cb3SPatrick Williams
24892b42cb3SPatrick Williams    finally:
24992b42cb3SPatrick Williams        cleanupcontrol(root)
25092b42cb3SPatrick Williams        bb.utils.unlockfile(lf)
25192b42cb3SPatrick Williams
25292b42cb3SPatrick Williams# Have to list any variables referenced as X_<pkg> that aren't in pkgdata here
25392b42cb3SPatrick WilliamsIPKEXTRAVARS = "PRIORITY MAINTAINER PACKAGE_ARCH HOMEPAGE PACKAGE_ADD_METADATA_IPK"
25492b42cb3SPatrick Williamsipk_write_pkg[vardeps] += "${@gen_packagevar(d, 'IPKEXTRAVARS')}"
25592b42cb3SPatrick Williams
25692b42cb3SPatrick Williams# Otherwise allarch packages may change depending on override configuration
25792b42cb3SPatrick Williamsipk_write_pkg[vardepsexclude] = "OVERRIDES"
25892b42cb3SPatrick Williams
25992b42cb3SPatrick Williams
26092b42cb3SPatrick WilliamsSSTATETASKS += "do_package_write_ipk"
26192b42cb3SPatrick Williamsdo_package_write_ipk[sstate-inputdirs] = "${PKGWRITEDIRIPK}"
26292b42cb3SPatrick Williamsdo_package_write_ipk[sstate-outputdirs] = "${DEPLOY_DIR_IPK}"
26392b42cb3SPatrick Williams
26492b42cb3SPatrick Williamspython do_package_write_ipk_setscene () {
26592b42cb3SPatrick Williams    tmpdir = d.getVar('TMPDIR')
26692b42cb3SPatrick Williams
26792b42cb3SPatrick Williams    if os.access(os.path.join(tmpdir, "stamps", "IPK_PACKAGE_INDEX_CLEAN"), os.R_OK):
26892b42cb3SPatrick Williams        os.unlink(os.path.join(tmpdir, "stamps", "IPK_PACKAGE_INDEX_CLEAN"))
26992b42cb3SPatrick Williams
27092b42cb3SPatrick Williams    sstate_setscene(d)
27192b42cb3SPatrick Williams}
27292b42cb3SPatrick Williamsaddtask do_package_write_ipk_setscene
27392b42cb3SPatrick Williams
27492b42cb3SPatrick Williamspython () {
27592b42cb3SPatrick Williams    if d.getVar('PACKAGES') != '':
27692b42cb3SPatrick Williams        deps = ' opkg-utils-native:do_populate_sysroot virtual/fakeroot-native:do_populate_sysroot xz-native:do_populate_sysroot'
27792b42cb3SPatrick Williams        d.appendVarFlag('do_package_write_ipk', 'depends', deps)
27892b42cb3SPatrick Williams        d.setVarFlag('do_package_write_ipk', 'fakeroot', "1")
27992b42cb3SPatrick Williams}
28092b42cb3SPatrick Williams
28192b42cb3SPatrick Williamspython do_package_write_ipk () {
28292b42cb3SPatrick Williams    bb.build.exec_func("read_subpackage_metadata", d)
28392b42cb3SPatrick Williams    bb.build.exec_func("do_package_ipk", d)
28492b42cb3SPatrick Williams}
28592b42cb3SPatrick Williamsdo_package_write_ipk[dirs] = "${PKGWRITEDIRIPK}"
28692b42cb3SPatrick Williamsdo_package_write_ipk[cleandirs] = "${PKGWRITEDIRIPK}"
28792b42cb3SPatrick Williamsdo_package_write_ipk[depends] += "${@oe.utils.build_depends_string(d.getVar('PACKAGE_WRITE_DEPS'), 'do_populate_sysroot')}"
28892b42cb3SPatrick Williamsaddtask package_write_ipk after do_packagedata do_package do_deploy_source_date_epoch before do_build
28992b42cb3SPatrick Williamsdo_build[rdeptask] += "do_package_write_ipk"
29092b42cb3SPatrick Williams
29192b42cb3SPatrick WilliamsPACKAGEINDEXDEPS += "opkg-utils-native:do_populate_sysroot"
29292b42cb3SPatrick WilliamsPACKAGEINDEXDEPS += "opkg-native:do_populate_sysroot"
293