#!/bin/bash
# vim: ts=4 sw=4 ai noet
# $Id$
#
# Copyright (C) 2008, Robert Nelson. Licensed under GPLv2.
# By Robert Nelson.
#
# Portions originally:
# Copyright (C) 2005 by SWsoft. Licensed under QPL.
# By Kir Kolyshkin.

TOOLDIR=/usr/share/vzpkg2

. ${TOOLDIR}/functions

# Returns -c parameters needed for yum.
function yum_conf()
{
	local yum_conf_file=/var/tmp/yum.conf.$$

	read_vzpkg_conf

	if test -n "$YUM_CONF"; then
		echo "$YUM_CONF" > $yum_conf_file
	else
		local cfg=`find_template_config_file yum.conf`
		test -f "$cfg" || abort "yum repository config file yum.conf not found!"
		cp "$cfg" $yum_conf_file
	fi
	echo "-c $yum_conf_file"
}

# Import gpgkeys from OS template's config/gpgkeys directory to the VE.
# Parameters:
# Environment: VE_ROOT should be set.
function import_gpgkeys()
{
	test -z "$VE_ROOT" && abort "$FUNCNAME: VE_ROOT not set"
	local keydir=`find_template_config_file gpgkeys`
	test -d "$keydir" || return
	local files="$keydir/*"
	
	if ! test -z "$files"; then
		log4 "Importing RPM GPG keys: $files"
		rpm --root $VE_ROOT --import $files
	fi
}

function run_yum()
{
	# Dirty dirty hack for yum/rpm to read RPM macros from the file .rpmmacros
	# which resides in our template configuration directory. If you know a better
	# way of doing it, please enlighten me.
	local orig_HOME=$HOME
	local file=`find_template_config_file .rpmmacros`
	test -n "$file" && HOME=`dirname $file` || HOME=$TEMPLATE_DIR/config

	YUM_CONF_FILE=`yum_conf` || exit $?

	YUM_ARGS="--installroot=$VE_ROOT $YUM_CONF_FILE -y"

	log4 "Running yum $YUM_ARGS $*"
	yum $YUM_ARGS $*
	local rc=$?

	rm -f /usr/tmp/yum.conf.$$
	rm -rf $VE_ROOT/var/cache/yum/* $VE_ROOT/var/cache/yum/.gpg* 
	rm -rf $VE_ROOT/var/log/yum.log
	rm -rf $VE_ROOT/vz

	HOME=$orig_HOME

	return $rc
}

function run_rpm()
{
	# Dirty dirty hack for yum/rpm to read RPM macros from the file .rpmmacros
	# which resides in our template configuration directory. If you know a better
	# way of doing it, please enlighten me.
	local orig_HOME=$HOME
	local file=`find_template_config_file .rpmmacros`
	test -n "$file" && HOME=`dirname $file` || HOME=$TEMPLATE_DIR/config

	RPM_ARGS="--root=$VE_ROOT"

	log4 "Running rpm $RPM_ARGS"
	rpm $RPM_ARGS $*
	local rc=$?

	HOME=$orig_HOME

	return $rc
}
