#!/bin/bash
# -*- coding: utf-8; mode: sh; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:ft=sh:et:sw=4:ts=4:sts=4

# Note:
# This script is sourced by the mpbb wrapper script.
# Do not execute this directly!

gather-archives-usage() {
    # "prog" is defined in mpbb-help.
    # shellcheck disable=SC2154
    cat <<EOF
usage: $prog [<global opts>] gather-archives [<opts>]

Copy unpublished, distributable archives of active ports into a staging
directory for uploading.

Options:

  --archive-site=<URL>
    URL of a mirror to check for preexisting archives. Defaults to
    \`https://packages.macports.org'.

  --staging-dir=<path>
    A directory for storing distributable archives before deployment.
    Defaults to the \`archive-staging' subdirectory of the \`--work-dir'
    working directory.

Run \`$prog help' for global options and a list of other subcommands.
EOF
}

gather-archives() {
    local args
    parseopt archive-site:,staging-dir: "$@" || return
    : "${option_archive_site=https://packages.macports.org}"
    # shellcheck disable=SC2154
    : "${option_staging_dir=${option_work_dir}/archive-staging}"
    # shellcheck disable=SC2086
    set -- ${args+"${args[@]}"}

    # $option_prefix is set in mpbb
    # shellcheck disable=SC2154
    tclsh=${option_prefix}/bin/port-tclsh

    if [ -d "${option_staging_dir}" ]; then
        find "${option_staging_dir}" -type f -delete -print | sed -E -e "s|^.*/||" -e 's/^/Deleting previously staged archive: /'
        rm -rf "${option_staging_dir}"
        echo
    fi

    mkdir -p "${option_staging_dir}" || return

    status=0
    for archive_path in $("${option_prefix}/bin/port" -q location active); do
        archive_port=$(basename "$(dirname "${archive_path}")")
        archive_basename=$(basename "${archive_path}")

        if ! curl -fIsL "${option_archive_site}/${archive_port}/${archive_basename}" > /dev/null; then
            # $option_jobs_dir is set in mpbb
            # shellcheck disable=SC2154
            if "${tclsh}" "${option_jobs_dir}/port_binary_distributable.tcl" -v "${archive_port}"; then
                echo "Staging archive for upload: ${archive_basename}"
                mkdir -p "${option_staging_dir}/${archive_port}" || { status=$?; break; }
                ln "${archive_path}" "${option_staging_dir}/${archive_port}/${archive_basename}" || { status=$?; break; }
            fi
        else
            echo "Archive was already uploaded: ${archive_basename}"
        fi
    done

    return $status
}