#!/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!

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

Install or update the auxiliary MacPorts base installation. (To reindex
port sources, use \`$prog checkout'.)

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

selfupdate() {
    # $option_prefix is set in mpbb
    # shellcheck disable=SC2154
    if [ ! -f "${option_prefix}/bin/port" ]; then
        macports_version=2.3.4
        macports_distname=MacPorts-${macports_version}
        macports_distfile=${macports_distname}.tar.bz2
        if [ ! -d ${macports_distname} ]; then
            if [ ! -f ${macports_distfile} ]; then
                curl -fsLO https://distfiles.macports.org/MacPorts/${macports_distfile} || return
            fi
            tar -xjf ${macports_distfile} || return
        fi
        cd ${macports_distname} || return
        ./configure --prefix="${option_prefix}" --enable-readline || return
        make -j"$(sysctl -n hw.activecpu)" || return
        make install || return
        cd .. || return
        rm -rf ${macports_distfile} ${macports_distname} || return
    fi

    "${option_prefix}/bin/port" -d selfupdate --nosync || return
}