#!/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
    ;;

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
	# meta.txz should be time stamped with the latest update
	# to the package repo
	vers=$(uname -r)
	arch=$(uname -m)
	tmpfile=auto-pkg-branch-summary.tgz
	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
