#!/bin/sh -e

##########################################################################
#   Script description:
#       Determine the branch of the current ports tree
#       
#   History:
#   Date        Name        Modification
#   2020-04-16  Charlie &   Begin
##########################################################################

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


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

if [ $# != 0 ]; then
    usage
fi

case $(auto-ostype) in
FreeBSD)
    : ${PORTSDIR:=/usr/ports}
    export PORTSDIR

    if ! which git > /dev/null 2>&1; then
	if [ $(id -u) = 0 ]; then
	    printf "$0: Installing git...\n" >> /dev/stderr
	    pkg install -y git > /dev/null 2>&1
	else
	    printf "$0: You must install git before running this script.\n" >> /dev/stderr
	    printf "$0: Run 'pkg install git' as root.\n" >> /dev/stderr
	    exit 1
	fi
    fi

    cd $PORTSDIR
    # FIXME: Remove svn support
    if [ -e .svn ]; then
	if svn info | grep -q '^URL.*head$'; then
	    branch=latest
	else
	    branch=$(svn info | awk -F / '$1 ~ "^URL" { print $NF }')
	fi
	printf "$branch\n"
    elif [ -e .git ]; then
	if ! git branch > /dev/null; then
	    printf "$0: Cannot determine git branch.\n"
	    exit 1
	fi
	git_branch=$(git branch | awk '$1 == "*" { print $2 }')
	if [ 0"$git_branch" = 0main ]; then
	    branch=latest
	else
	    branch=$git_branch
	fi
	printf "$branch\n"
    else
	# Portsnap trees should have "head" in Makefile
	if head -1 $PORTSDIR/Makefile | fgrep -q head; then
	    printf "latest\n"
	else
	    printf "$0: Cannot determine ports branch from $PORTSDIR/Makefile.\n"
	    exit 1
	fi
    fi
    ;;

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

esac
