#!/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
	printf "$0: Installing git...\n" >> /dev/stderr
	pkg install -y git > /dev/null 2>&1
    fi

    cd $PORTSDIR
    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
	git_branch=$(git branch | awk '{ print $2 }')
	if [ $git_branch = main ]; 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
