#!/bin/bash

# Random integrity things
[ "$UID" = "" ] && UID=$(uid)

if [ -z "$BASEDIR" ]; then
	BASEDIR="$(dirname $0)"
fi

if [ -f "$BASEDIR/config" ]; then
	. "$BASEDIR/config"
fi

# Useful functions
source_makepkg () {
	if [ -f "/etc/makepkg.conf" ]; then
		#Get some config info
		. /etc/makepkg.conf
	else
		echo "/etc/makepkg.conf does not exist!"
		exit 1
	fi
}

UMASK=""
set_umask () {
	[ "$UMASK" == "" ] && UMASK="$(umask)"
	umask 002
}

restore_umask () {
	umask $UMASK
}

repo_lock () { #repo_lock repo-name arch
	LOCKFILE="$TMPDIR/.repolock.$1.$2"
	if [ -f "$LOCKFILE" ]; then
		owner="$(/usr/bin/stat -c %U $LOCKFILE)"
		echo "error: db generation is already in progress (started by $owner)"
		exit 1
	else
		/bin/touch "$LOCKFILE"
		set_umask
	fi
}

repo_unlock () { #repo_unlock repo-name arch
	LOCKFILE="$TMPDIR/.repolock.$1.$2"
	if [ ! -f "$LOCKFILE" ]; then
		echo "error: repo lock doesn't exist... something went terribly wrong!"
	else
		rm -f "$LOCKFILE"
	fi
	restore_umask
}

# Get the package name from the filename
# hackish, but should work for now
getpkgname() {
	local tmp

	tmp=${1##*/}
	tmp=${tmp%$PKGEXT}
	tmp=${tmp%$SRCEXT}
	tmp=${tmp%-$CARCH}
	echo ${tmp%-*-*}
}

# Get the pkgver-pkgrel of this package
getpkgver() {
	local tmp

	tmp=${1##*/}
	tmp=${tmp%$PKGEXT}
	tmp=${tmp%$SRCEXT}
	tmp=${tmp%-$CARCH}
	echo $tmp | sed 's|.*-\(.*-.*\)$|\1|g'
}

check_pkg_arch () { #check_pkg_arch pkgfile arch
	local arch
	_arch="$(/usr/bin/bsdtar -xOf "$1" .PKGINFO | /bin/grep "^arch" | /bin/sed 's|\w*\s*=\s*\(.*\)|\1|')"

	if [ -z "$_arch" ]; then
		echo "ERROR: Package '$1' has no arch in the PKGINFO. Fail!"
		return 1
	fi
	if [ "$_arch" = "$2" ]; then
		return 0
	else
		return 1
	fi
}

get_svnpath () { #get_svnpath reponame
	local var
	local repopath
	var="\$SVNREPO_${1}"

	eval repopath=${var}
	if [ -z "$repopath" ]; then
		echo "ERROR: SVN path not defined for '${1}'" >2
		echo "       Please check SVNREPO_${1} config setting" >2
	fi
	
	echo "$repopath"
}


# vim: set ts=4 sw=4 noet ft=sh: