# foundationpkgs usage quick reference

This repository stores package recipes as POSIX-compatible `APKBUILD` files. Treat `APKBUILD` as the source of truth; generated `PKGBUILD` and `*.pacscript` files are intermediates.

## Repository layout

Recipes live under applicability buckets:

```text
Linux/<pkg>/APKBUILD      # Linux-specific recipe
Darwin/<pkg>/APKBUILD     # macOS-specific recipe
Unix/<pkg>/APKBUILD       # generic Unix recipe
noarch/<pkg>/APKBUILD     # architecture-independent output
any/<pkg>/APKBUILD        # fully generic fallback
x86_64-linux/<pkg>/...    # legacy/explicit target bucket also present
pacscripts/               # legacy/generated-style pacstall/Arch scripts
scripts/                  # build/conversion/CI helpers
```

Recipe lookup order for `scripts/build.sh <pkgname>` is:

```text
$(canonical_os)/ -> Unix/ -> noarch/ -> any/
```

On Windows, `Unix/` is skipped.

## Validate scripts after changes

Run before committing script or CI changes:

```sh
for file in scripts/*.sh tests/*.sh; do sh -n "$file" || exit; done
for test in tests/*.sh; do sh "$test" || exit; done
scripts/fpkgs-ci.sh plan HEAD
```

If touching a recipe, run a targeted build when possible.

## Build one package locally

By package name:

```sh
scripts/build.sh authelia-fcgi-authz
```

By recipe path:

```sh
scripts/build.sh x86_64-linux/authelia-fcgi-authz/APKBUILD
scripts/build.sh noarch/movements/APKBUILD
```

Choose output directory:

```sh
scripts/build.sh -o dist noarch/movements/APKBUILD
```

Keep temporary workdir for debugging:

```sh
scripts/build.sh -k noarch/movements/APKBUILD
```

Cross-target build:

```sh
scripts/build.sh -t x86_64-unknown-linux-musl Unix/kcgi/APKBUILD
```

### Format, target, and prerequisites

On Linux the default is **genuine APK output through upstream abuild**, targeting
`<host-arch>-alpine-linux-musl`. Other hosts retain tar.gz output and their native
target. Choose independently with `-f`/`FPKGS_FORMAT` and `-t`/`FPKGS_TARGETS`.
An opt-in `deb` backend is also available for Debian 13 amd64 recipes:

```sh
scripts/build.sh -f apk -t x86_64-alpine-linux-musl Unix/kcgi/APKBUILD
scripts/build.sh -f tar.gz Unix/kcgi/APKBUILD
FPKGS_FORMAT=tar.gz scripts/fpkgs-ci.sh plan HEAD
FPKGS_FORMAT=apk FPKGS_TARGETS=x86_64-unknown-linux-gnu scripts/fpkgs-ci.sh plan HEAD
```

The last example selects APK packaging for a GNU target; it is not an Alpine
ABI compatibility claim. Recipes, compilers, sysroots and runtime dependencies
remain the caller's responsibility. A target name does not convert libc.

Install upstream `abuild`/`apk-tools` before APK builds. Debian 13 amd64 bootstrap
`.deb` packages and build instructions live in `~/Projects/foundationpkgs-binaries`.
Run builds as an unprivileged user, generate a signing key with
`abuild-keygen -a -n`, and trust its **public** key for local index verification
(the bootstrap README documents the key installation). No keys are generated or
installed by foundationpkgs. `FPKGS_ABUILD` can select another abuild executable.

The APK backend runs `abuild -d` in a temporary copy of the recipe directory.
It leaves dependency provisioning to the caller and never installs APK build
dependencies into the Debian system root. Use upstream `CBUILDROOT`, compiler
variables and PATH for target dependencies/tools; `-s`/`-n` are legacy tar-only
staging options and are rejected for APK builds. ELF dependency tracing expects
a matching APK database, not dpkg. Configure it explicitly; tracing is not
silently disabled. Upstream skips execution checks on cross builds.

Outputs preserve upstream repository layout and signed indexes:

```text
dist/<target>/<recipe-bucket>/<apk-arch>/*.apk
dist/<target>/<recipe-bucket>/<apk-arch>/APKINDEX.tar.gz
# Each file also has a bare-digest .sha256 sidecar.
```

Explicit tar.gz output retains the old layout and semantics:

```text
dist/<target-or-noarch>/<pkgname>-<pkgver>-r<pkgrel>.tar.gz
dist/<target-or-noarch>/<pkgname>-<pkgver>-r<pkgrel>.tar.gz.sha256
```

### Debian output and APT servicing

```sh
scripts/build.sh -f deb -t x86_64-unknown-linux-gnu Unix/minimal-fxa-server/APKBUILD
```

The recipe must set `deb_pkgver` to a Debian-valid version (e.g.
`0+git20260225`), optionally `deb_depends` and `deb_postinst`. The latter must be
a local source/checksummed script. `pkgrel` supplies the Debian revision.
The backend runs the existing recipe's tar builder/checks in private staging,
then uses native `dpkg-deb --root-owner-group` without sudo or live APT changes.
It currently supports Linux builds for Debian amd64; other recipes must explicitly
opt in and declare appropriate runtime dependencies. The output is
`<pkgname>_<deb_pkgver>-<pkgrel>_amd64.deb` plus its SHA-256 sidecar.
The Debian backend normalizes payload/archive timestamps using `SOURCE_DATE_EPOCH`
(default: latest recipe-directory commit time, or zero outside Git) and maps
randomized native compiler build paths. Increment `pkgrel` whenever package bytes
change: the APT archive refuses to replace an existing version with different bytes.
Recipes declaring `arch="noarch"` (or legacy `any`) produce `_all.deb` with
`Architecture: all`, still under the requested Debian target directory.
Pacstall is not used: the installed Pacstall's build-only mode still invokes
sudo, which the CI build identity deliberately lacks.

CI selects Debian packages through `FPKGS_DEB_PACKAGES` in `.config/Jobfile`;
FxA is selected by default. `FPKGS_APK_PACKAGES` selects reviewed APK packages.
The helper's direct `FPKGS_FORMAT`/`FPKGS_PACKAGES` interface remains available.
Published `.deb` files are not themselves OpenPGP-signed: the separate
`foundationpkgs-binaries` publisher on `cdg-1` retains them and signs APT metadata
with its private archive key, unavailable to the build identity. See that repository's `docs/apt.md`.

## Service packaging

Author systemd units as the **single canonical source**. Do not maintain a second
handwritten init.d definition. Service recipes use the native build dependency
`initify` and call its checked staging helper from `package()`:

```sh
# APKBUILD (include example.service in source/checksums):
makedepends="initify"
package() {
    # Install application files first, then stage the target service integration.
    initify-package "${FPKGS_INIT_SYSTEM:?select systemd or openrc}" \
        "$pkgdir" "$srcdir/example.service"
}
```

Select the init system independently of package format/ABI, for example:

```sh
FPKGS_INIT_SYSTEM=openrc scripts/build.sh -f apk path/to/APKBUILD
FPKGS_INIT_SYSTEM=systemd scripts/build.sh -f deb -t x86_64-unknown-linux-gnu path/to/APKBUILD
```

`systemd` installs original units as mode 644 under `/usr/lib/systemd/system/`.
`openrc` converts services during the build and installs mode-755 scripts under
`/etc/init.d/`. There is no conversion on client installation and no automatic
service enablement. `FPKGS_INIT_SYSTEM` is part of the CI build key. Do not publish
different init payloads under an identical package name/version to the same
repository: choose one init variant per release channel, or distinct integration
package names when distributing both. No default is inferred from APK vs DEB.

The helper validates **all units before installing any**. For OpenRC it allows
only a conservative subset: `Description`, a single absolute `ExecStart` with
unquoted literal arguments, optional `/run/` `PIDFile`, and `Type=simple` (also the
systemd default when absent). `WantedBy=multi-user.target` is accepted only as
administrator enablement metadata; no runlevel is enabled. It runs `initify` in
private staging, adds foreground background/PID tracking for OpenRC, checks the
result with `sh -n`, and never modifies the canonical source. Unsupported types,
directives, shell expansions, instance specifiers, duplicate assignments, and
non-service OpenRC inputs fail the build. Whitespace normalization and quoting
outside this subset are intentionally rejected, not guessed.

In particular, `.path` watchers, timers, user/group changes, working directories,
environment files, pre-start commands and systemd sandbox settings need explicit
converter support before they can be packaged for OpenRC. The current stagit
queue units are **not supported** by this converter. systemd builds retain their
original behavior because those units are installed unchanged.

The foundationpkgs CI package job builds initify from the current revision and
stages it on its native PATH with `scripts/prepare-ci-tools.sh`; nothing is
installed into the host. The Debian and APK backends inherit that PATH. For
manual builds, use `toolbin=$(sh scripts/prepare-ci-tools.sh /absolute/work/path)`
and prepend it to PATH. A legacy archive build can also stage a previously built
initify archive from the same `-o` directory via `makedepends`. Other dependency
provisioning remains separate; do not add sudo or APT calls to recipes.

## CI/package planner

Plan work for a revision:

```sh
scripts/fpkgs-ci.sh plan HEAD
scripts/fpkgs-ci.sh plan <git-rev>
```

Run builds and publish artifacts:

```sh
scripts/fpkgs-ci.sh run HEAD
```

Print the build key for one recipe/target/rev:

```sh
scripts/fpkgs-ci.sh key noarch/movements/APKBUILD x86_64-unknown-linux-musl HEAD
```

Useful environment variables:

```sh
FPKGS_ROOT=$PWD
FPKGS_WORK_ROOT=/var/tmp/fpkgs-ci
FPKGS_DL_ROOT=/srv/http/dl.nply.org/foundationpkgs
FPKGS_DL_BASE_URL=https://nply.org/dl/foundationpkgs
FPKGS_FORMAT=apk  # or tar.gz; same default as scripts/build.sh
FPKGS_TARGETS="x86_64-alpine-linux-musl aarch64-alpine-linux-musl"
FPKGS_ABUILD=abuild
FPKGS_PACKAGES="minimal-fxa-server"  # optional name filter; unset means all discovered recipes
```

Published artifact layout:

```text
$FPKGS_DL_ROOT/<target>/<pkgname>/<pkgver>-r<pkgrel>/<buildkey>/
  <recipe-bucket>/<apk-arch>/*.apk     # APK format, including splits
  <recipe-bucket>/<apk-arch>/APKINDEX.tar.gz
  *.tar.gz                          # instead, for tar.gz format
  ...matching .sha256 sidecars...
  SHA256SUMS                        # all package/index files
  build.log
  manifest
```

Public URL is based on `$FPKGS_DL_BASE_URL`.

## CI integration

For push-triggered builds, effective Jobfile selection (including `integ`
precedence), exact-revision binary lookup, logs, and staged installation, use
[the CI workflow](ci.md). Routine packaging does not require reading runner or
publisher implementation scripts.

## Convert/install through pacstall helpers

Convert one APKBUILD to pacscript:

```sh
scripts/apkbuild-to-pacscript.sh path/to/APKBUILD
```

Install through pacstall from APKBUILD source:

```sh
scripts/pacstall-install.sh <pkgname-or-path>
```

## Adding a new recipe

1. Pick the narrowest correct bucket.
2. Create `<bucket>/<pkg>/APKBUILD`.
3. Keep it POSIX `sh`; no bashisms.
4. Include local source files beside the APKBUILD if needed.
5. Use `source="..."` for remote and local inputs.
6. Add checksums for fixed remote archives when possible.
7. Build locally:

```sh
scripts/build.sh <bucket>/<pkg>/APKBUILD
```

8. Validate syntax with `sh -n <recipe-path>` and run `git diff --check`.
9. When CI deployment is authorized, commit and push, then follow
   [binary lookup](ci.md#check-a-binary). `plan HEAD` reads the committed revision,
   not an untracked or uncommitted recipe; use the targeted build for WIP.

### Builder contract

**APK:** `scripts/build.sh -f apk` delegates recipe interpretation, prepare/build/
check/package phases, splitting, metadata, signing and indexing to upstream
abuild. Use Alpine's real recipe conventions: `arch="noarch"` rather than `any`,
and full subpackage names such as `subpackages="$pkgname-dev $pkgname-doc"`.
Custom `verify()`-only recipes and short split suffixes are legacy extensions,
not an upstream recipe contract. Existing recipes need review before switching
their production builds; selecting a new format does not migrate recipes.

**Legacy tar.gz:** `scripts/build.sh -f tar.gz` sources the APKBUILD as POSIX shell, fetches/unpacks sources,
applies listed `.patch` sources through `default_prepare`, then runs `build()`
and `package()`. It does not call a recipe's `prepare()` hook. Build/package
functions start in `$builddir`; it defaults to `$srcdir`. Prefer an explicit
`builddir="$srcdir/$pkgname-$pkgver"` when the source archive has that root.
`$pkgdir` is staging, not the live system; install only beneath it.

The tar.gz builder **does not automatically run `check()`**, and it calls
`build()` even when `options="!build"` is present. Invoke `check` explicitly from
`build()` when needed; for prebuilt/data-only packages define `build() { :; }`.
`options` metadata may be used by other tooling, but is not a phase-control
interface for this builder.

For Unix-wide recipes, use portable `mkdir -p` plus `install -m`; GNU
`install -D` is not portable to the macOS host. Set executable/data modes
explicitly. An example with checks and two native binaries is
[`Unix/minimal-fxa-server/APKBUILD`](../Unix/minimal-fxa-server/APKBUILD).

## APKBUILD conventions in this repo

Minimum shape:

```sh
pkgname=example
pkgver=0.1.0
pkgrel=0
pkgdesc="Short description"
url="https://example.org"
arch="all"        # or noarch
license="MIT"
depends=""
makedepends=""
source="..."
builddir="$srcdir/$pkgname-$pkgver"

build() {
    make
    # Run upstream checks here if supplied; check() is not called automatically.
}

package() {
    mkdir -p "$pkgdir/usr/bin"
    install -m755 example "$pkgdir/usr/bin/example"
}
```

The legacy tar.gz backend supports split packages with functions named after the suffix:

```sh
subpackages="assets"

assets() {
    pkgdesc="Public static assets"
    depends=""
    mkdir -p "$subpkgdir/usr/share/example"
    install -m644 file "$subpkgdir/usr/share/example/file"
}
```

Built subpackage tarballs are named:

```text
<pkgname>-<suffix>-<pkgver>-r<pkgrel>.tar.gz
```

## Package examples added for ops

Authelia FastCGI authorizer:

```text
x86_64-linux/authelia-fcgi-authz/APKBUILD
```

Build:

```sh
scripts/build.sh x86_64-linux/authelia-fcgi-authz/APKBUILD
```

Movements PHP app with split assets package:

```text
noarch/movements/APKBUILD
```

Build:

```sh
scripts/build.sh noarch/movements/APKBUILD
```

Produces base app package and `movements-assets` subpackage.

## Gotchas

- Keep scripts POSIX `sh`; avoid arrays, `[[ ]]`, `local`, `pipefail`, process substitution.
- `depends` and `makedepends_host` are staged into the target sysroot.
- `makedepends` and `makedepends_build` are staged into native root and placed on `PATH`.
- If a dependency has no recipe, the build helper assumes it is a host/base tool and warns.
- Changes that affect output must affect the build key. Local files listed in `source` are included in the key.
- Do not commit generated package outputs or CI artifacts.
