#!/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.10.5
        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
        if [ "${option_prefix}" != "/opt/local" ]; then
            applications_dir_flag="--with-applications-dir=${option_prefix}/Applications/MacPorts"
        fi
        : "${applications_dir_flag=}"
        if [ "$(id -u)" -ne 0 ]; then
            install_user_and_group_flags="--with-install-user=$(id -un) --with-install-group=$(id -gn)"
        fi
        : "${install_user_and_group_flags=}"
        PATH=/usr/bin:/bin:/usr/sbin:/sbin ./configure \
            --prefix="${option_prefix}" \
            ${applications_dir_flag} \
            ${install_user_and_group_flags} \
            --enable-readline || return
        make -j"$(sysctl -n hw.activecpu)" || return
        make install || return
        cd .. || return
        rm -rf ${macports_distfile} ${macports_distname} || return
    fi

    # selfupdate at most once every 12 hours
    if [[ ! -f selfupdate.timestamp || $(($(date +%s) - $(stat -f %m selfupdate.timestamp))) -gt 43200 ]]; then
        "${option_prefix}/bin/port" -d selfupdate --no-sync || return
        touch selfupdate.timestamp
    fi
}
