#!/bin/sh -e

##########################################################################
#   Script description:
#       Determine the ports branch from which packages are installed
#       
#   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)
    if awk '$1 == "url:" { print $2 }' /usr/local/etc/pkg/repos/*.conf \
	    2> /dev/null | fgrep -q latest; then
	printf "latest\n"
    elif awk '$1 == "url:" { print $2 }' /etc/pkg/*.conf | fgrep -q latest; then
	printf "latest\n"
    else
	# meta.txz should be time stamped with the latest update
	# to the package repo
	major=$(uname -r | cut -d . -f 1)
	arch=$(uname -p)
	tmpfile=auto-pkg-branch-meta.txz
	rm -f $tmpfile
	fetch -o $tmpfile \
	    http://pkg.freebsd.org/FreeBSD:$major:$arch/quarterly/meta.txz
	
	mod_time=$(ls -l -D '%Y-%m' $tmpfile | awk '{ print $6 }')
	rm -f $tmpfile
	year=$(echo $mod_time | cut -d - -f 1)
	# leading 0 means octal, invalid for 8 and 9
	padded_month=$(echo $mod_time | cut -d - -f 2)
	month=${padded_month#0}
	quarter=$((($month - 1) / 3 + 1))
	branch=${year}Q$quarter
	
	printf "$branch\n"
    fi
    ;;

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

esac
