#!/bin/sh -e

##########################################################################
#   Script description:
#       Mark a package to be rebuilt from source by auto-update-system
#       
#   History:
#   Date        Name        Modification
#   2021-01-13  Jason Bacon Begin
##########################################################################

usage()
{
    cat << EOM

Usage: $0 category/package[@flavor] reason

Marks a port for reinstalling from source by auto-update-system.  This
may be desirable to restore port options clobbered by "pkg upgrade",
upgrade ports that cannot be packaged, or build with optimized CFLAGS set
in /etc/make.conf.

FreeBSD ports: If the port/package supports flavors and no flavor is
specified, the default flavor is assumed.

The "reason" argument must not contain spaces.  It is a brief message that
will be displayed by auto-upgrade-system when rebuilding a package from
source.

Examples:

    $0 audio/lame license
    $0 math/openblas optimization
    $0 math/R build-options
    $0 wip/auto-admin work-in-progress

EOM
    exit 1
}


##########################################################################
#   Main
##########################################################################

if [ $# -ne 2 ]; then
    usage
fi
pkg=$1
if ! echo $pkg | fgrep -q '/'; then
    usage
fi
if echo $pkg | fgrep -q '@'; then
    flavor=$(echo $pkg | cut -d @ -f 2)
    pkg=$(echo $pkg | cut -d @ -f 1)
fi
reason=$2

case $(auto-ostype) in
FreeBSD)
    : ${PORTSDIR:=/usr/ports}
    if [ ! -e "$PORTSDIR/$pkg" ]; then
	printf "$PORTSDIR/$pkg: No such port.\n"
	exit 1
    fi
    mkdir -p $(auto-localbase)/etc/auto-admin
    # Check for port/package name only.  Don't duplicate if reason differs.
    auto-append-line $pkg "$pkg $reason $flavor" \
	$(auto-localbase)/etc/auto-admin/install-from-source nocomment
    ;;

*)
    # FIXME: Can this be merged with the FreeBSD case?
    # auto-pkgsrc-{dir|prefix} exit non-zero if no tree found
    PKGSRC=$(auto-pkgsrc-dir) || true
    if [ ! -e "$PKGSRC/$pkg" ]; then
	printf "$PKGSRC/$pkg: No such package.\n"
	exit 1
    fi
    PREFIX=$(auto-pkgsrc-prefix) || true
    if [ -z "$PREFIX" ]; then
	printf "$0: No active pkgsrc tree found.\n"
	exit 1
    fi
    mkdir -p $PREFIX/etc/auto-admin
    auto-append-line $pkg "$pkg $reason" \
	$PREFIX/etc/auto-admin/install-from-source nocomment
    ;;

esac
