#!/bin/sh -e

##########################################################################
#   Script description:
#       Check out a free ports tree
#       
#   History:
#   Date        Name        Modification
#   2017-02-15  Jason Bacon Begin
##########################################################################

usage()
{
    printf "Usage: $0\n"
    exit 1
}


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

: ${PORTSDIR:=/usr/ports}
export PORTSDIR

case $(auto-ostype) in
FreeBSD)
    if [ -e $PORTSDIR/CHANGES ]; then
	printf "Ports tree already installed in $PORTSDIR.\n"
	exit 1
    fi

    repo_branch=$(auto-pkg-branch)
    # Debug:
    # repo_branch=2021Q1
    printf "Binary packages are using the $repo_branch branch.\n"
    case $repo_branch in
    latest)
	git_branch=''
	;;
    
    *)
	git_branch="--branch $repo_branch"
	;;

    esac

    if ! which git; then
	pkg install -y git
    fi

    # FIXME: Factor out to something like $(auto-os-variant)
    if [ $(auto-os-variant) = GhostBSD ]; then
	printf "Cloning GhostBSD ports...\n"
	git clone --depth 1 \
	    https://github.com/ghostbsd/ghostbsd-ports $PORTSDIR
    else
	git clone --depth 1 \
	    https://git.FreeBSD.org/ports.git $git_branch --single-branch \
	    $PORTSDIR
    fi
    ;;

DragonFly)
    cd /usr
    make dports-create-shallow
    ;;

OpenBSD)
    # FIXME: Use CVS.  Requires choosing an anoncvs mirror.
    cd /usr
    ftp https://cdn.openbsd.org/pub/OpenBSD/$(uname -r)/{ports.tar.gz,SHA256.sig}
    signify -Cp /etc/signify/openbsd-$(uname -r | cut -c 1,3)-base.pub -x SHA256.sig ports.tar.gz
    tar xzf ports.tar.gz
    rm -f ports.tar.gz
    ;;

*)
    auto-unsupported-os $0
    exit 1
    ;;

esac
