#!/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
	# Determine latest branch that *should* exist based on today's date
	year=$(date +%Y)                # E.g. 2024
	month=$(date +%m)               # E.g. 11
	quarter=$(($month / 3 + 1))     # 11 / 3 + 1 = 4
	branch=${year}Q$quarter         # 2024Q4
	
	# Branch may not happen immediately at midnight of Jan, April,
	# Jul, Oct 1, so check for existence of the ports branch and
	# back up 1 quarter if it's not there yet.
	# Note: We assume that the new quarterly package repo is created
	# at the same moment as the ports branch.
	while ! git ls-remote --branches https://git.freebsd.org/ports.git | grep -q "/$branch$"; do
	    if [ $quarter = 1 ]; then
		year=$(($year - 1))
		quarter=4
	    else
		quarter=$(($quarter - 1))
	    fi
	    branch=${year}Q$quarter
	done
	
	printf "$branch\n"
    fi
    ;;

NetBSD)
    # FIXME: Find a deterministic way to glean the quaterly branch
    # instead of relying on time stamps
    if awk '$1 == "url:" { print $2 }' /usr/pkg/etc/pkgin/repositories.conf \
	    2> /dev/null | fgrep -q pkgsrc.smartos.org; then
	printf "latest\n"
    else
	# pkg_summary.gz should be time stamped with the latest update
	# to the package repo
	vers=$(uname -r)
	arch=$(uname -m)
	tmpfile=auto-pkg-branch-summary.gz
	rm -f $tmpfile
	# echo 'https://cdn.netbsd.org/pub/pkgsrc/packages/NetBSD/amd64/9.3/All/pkg_summary.gz'
	fetch -o $tmpfile \
	    https://cdn.netbsd.org/pub/pkgsrc/packages/NetBSD/$arch/$vers/All/pkg_summary.gz
	
	mod_time=$(stat -t '%Y-%m' $tmpfile | awk '{ print $10 }' | tr -d '"')
	year=${mod_time%-*}
	month=${mod_time#*-}
	# leading 0 means octal, invalid for 8 and 9
	padded_month=$(echo $mod_time | cut -d - -f 2)
	month=${padded_month#0}
	rm -f $tmpfile
	quarter=$((($month - 1) / 3))
	branch=${year}Q$quarter
	
	printf "$branch\n"
    fi
    
    ;;

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

esac
