#!/bin/bash

# Print help and exit
usage(){
	echo "-- $0 --"
	echo "Freeze package environement in distributions. Create a 'fake' repository with real repodata but symbolic link of rpms"
	echo "$0 OrigDir/repmod.xml BaseRepoDir DestDistributionBasenaemeDir"
	exit 
}

# Print the first arguement, execute the rest of the arguements and print the result OK/FAILED
action(){
	echo -ne "${1} : " 
	shift
	$@ &> /tmp/aaa
	[[ $? -eq 0 ]] && echo -e '\033[0;32mOK\033[0m' || echo -e '\033[0;31mFAILED\033[0m'
}

# Create tree structure of the repository in the destination directory
CreateEnv(){
	CptErr=0
	[[ ! -d ${DirDest} ]] && mkdir -p ${DirDest} || true
	CptErr=$((CptErr + $?))
	for Dir in $(find -L $OrigBaseRepo -type d| sed "s#${OrigBaseRepo}##g")
		do
			[[ ! -d ${DirDest}/${Dir} ]] && mkdir -p ${DirDest}/${Dir} || true
			CptErr=$((CptErr + $?))
		done

	CptErr=$((CptErr + $?))
	return $CptErr
	}

# for each rpm in the (get)Package directory, create a symbolic link in the destination directory
RpmLink(){
	CptErr=0
	for Rpm in $(find -L $OrigBaseRepo -type f -name "*.rpm" | sed "s#${OrigBaseRepo}##g")
		do
			[[ ! -L ${DirDest}/${Rpm} ]] && ln -s ${OrigBaseRepo}${Rpm} ${DirDest}/${Rpm} || true
			CptErr=$((CptErr + $?))
		done
	return $CptErr
}

# Copy repodata files in the destination directory
RepoModCopy(){
	cp -vf $(dirname ${RepModFile})/* $(dirname $(echo ${RepModFile}| sed "s#${BaseDirDestRepo}#${DestDir}#g"))/.
	CptErr=$((CptErr + $?))
	return $?
}

# Check all arguments and create variable environement for readability
CheckArg(){
	[[ ! -f ${1} ]] && usage
	RepModFile=${1}
	[[ ! -d ${2} ]] && usage
	BaseDirDestRepo=${2}
	DestDir=${3}/distributions/
	DirDest=$(echo $(dirname $(dirname ${RepModFile})) | sed "s#${BaseDirDestRepo}#${DestDir}#g")
	OrigBaseRepo=$(echo $(dirname $(dirname ${RepModFile})))
}


# Main

CheckArg ${1} ${2} ${3}
echo "
###############################################
	RepModFile      = ${1}
	BaseDirDestRepo = ${2}
	DestDir         = ${3}
###############################################"

# Execute 

action "Create dest environement" CreateEnv ${RepModFile} ${BaseDirDestRepo} ${DestDir}
action "Link Rpm" RpmLink ${RepModFile} ${BaseDirDestRepo} ${DestDir}
action "Copy repo data" RepoModCopy ${RepModFile} ${BaseDirDestRepo} ${DestDir}


