#!/usr/bin/env modbuild

# Custom prep instead of urls: in config.yaml — modbuild's builtin curl has
# no retry/resume, so an interrupted 3.7 GB download restarts from zero and
# leaves a partial file the next prep reuses silently. wget --continue
# resumes it, and gzip -t gates the build on an intact tarball.
# sid= in the URL is session-generated on ccp4.ac.uk and expires; on download
# failure get a fresh link from https://www.ccp4.ac.uk/download/ (package
# "CCP4 + SHELX + ARP/wARP", Linux x86_64), or pre-stage the tarball by hand
# in $PMODULES_DISTFILESDIR under the name below.
pbuild::prep() {
    local -r tarball="${PMODULES_DISTFILESDIR}/ccp4-${V}-shelx-arp-x86_64.tar.gz"
    local -r url='https://www.ccp4.ac.uk/download/download_file.php?os=linux&pkg=ccp4-shelx-arp-x86_64&sid=09b78d1369f605f517efa393f88d2bae713ad0b6'
    if ! gzip -t "${tarball}" 2>/dev/null; then
        mkdir -p "${PMODULES_DISTFILESDIR}"
        wget --continue --tries=20 --waitretry=30 \
             --output-document="${tarball}" "${url}" || \
            std::die 42 "ccp4: download failed — quota/disk full, or expired sid (fetch a fresh link from https://www.ccp4.ac.uk/download/)"
        gzip -t "${tarball}" || \
            std::die 42 "ccp4: tarball fails gzip -t after download — re-run to resume, or rm it to restart"
    fi
}

pbuild::configure() {
    :
}

pbuild::compile() {
    :
}

pbuild::install() {
    cd "${PREFIX}"
    # modbuild has no errexit in hooks — without the die-guards a failed step
    # still ends in a "done" build with a broken PREFIX (happened 2026-08-18
    # with a truncated cached tarball).
    # untar straight from the distfiles cache — no point copying 3.7 GB into
    # SRC_DIR first (prep already verified it with gzip -t)
    tar -xzf "${PMODULES_DISTFILESDIR}/ccp4-${V}-shelx-arp-x86_64.tar.gz" || \
        std::die 42 "ccp4: untar failed — rm the tarball from the distfiles dir and re-run"
    # the 9-series tarball unpacks to ccp4-9 (NOT ccp4-9.0 as the install doc
    # implies) — glob instead of guessing the name
    local -a top=( ccp4-*/ )
    [[ -x "${top[0]}BINARY.setup" ]] || \
        std::die 42 "ccp4: ${top[0]}BINARY.setup not found — vendor layout changed, inspect ${PREFIX}"
    # Pre-agree the CCP4 licence so BINARY.setup skips its interactive prompt
    # (downloading from ccp4.ac.uk already required accepting it). The printf
    # answers any prompt a newer BINARY.setup might still ask; printf instead
    # of `yes` because modbuild runs with pipefail and yes dies by SIGPIPE.
    touch "${PREFIX}/.agree2ccp4v6" "${HOME}/.agree2ccp4v6"
    printf 'y\ny\ny\n' | "./${top[0]}BINARY.setup" || \
        std::die 42 "ccp4: BINARY.setup failed"
    # version-independent symlink so the modulefile survives 9.x updates
    ln -sfn "${top[0]%/}" ccp4
    [[ -r ccp4/bin/ccp4.setup-sh ]] || \
        std::die 42 "ccp4: ccp4/bin/ccp4.setup-sh missing after setup — the modulefile would be broken"
}
