#!/bin/sh
# check and create pkg/repos configuration if it not exist
# $1 - path to root

if [ -z "${1}" ]; then
	echo "Usage: $0 [ -t skelfile ] [ -v ver ] [ -a arch ] [ -s stable ] [ -x url_schema (default: pkg+http)] <root path>"
	exit
fi

while getopts "v:a:s:x:t:" opt; do
	case "$opt" in
		v) ver="$OPTARG" ;;
		a) arch="$OPTARG" ;;
		s) stable="$OPTARG" ;;
		x) schema="${OPTARG}" ;;
		t) pkg_skel="${OPTARG}" ;;
	esac
	shift $(($OPTIND - 1))
done

rootdir=$1

[ ! -d "${rootdir}/usr/local/etc/pkg/repos" ] && mkdir -p ${rootdir}/usr/local/etc/pkg/repos
repos_cfg=`ls -1 ${rootdir}/usr/local/etc/pkg/repos`

[ -n "${repos_cfg}" ] && exit  # something presents, no action
[ ! -f "${pkg_skel}" ] && exit

[ -z "${arch}" -o "${arch}" = "native" ] && arch=`uname -m`
[ "${arch}" = "x86_64" ] && arch="amd64"
[ -z "${ver}" -o "${ver}" = "native" ] && ver=`sysctl -n kern.osrelease|cut -d - -f 1`
[ "${stable}" = "1" ] && ver=${ver%%.*}
[ -z "${rev}" ] && rev="head"
[ "${ver}" = "head" ] && ver="11.0"
[ -z "${schema}" ] && schema="pkg+http"

sed -Ees:MYVER:${ver}:g -es:MYARCH:${arch}:g -es:MYSCHEMA:${schema}:g ${pkg_skel} > ${rootdir}/usr/local/etc/pkg/repos/pkg.conf
