#!/bin/bash

HLP(){
echo "
$0 - utility to create an empty rpm package which contains the Requires and Provides tags.
Use it to install enemy rpm packages with non-native ROSA rpm names in the Requires tags.

"
cat $0 |sed -n '/;;[[:space:]].*###/s/).*###/ - /p'
echo "
example: $0 -r \"lib64foo lib64bar\" -p \"libfoo libbar\" -l /usr/bin/foo:/bin/foo -o foo-requires -b
"
exit ${LINENO}
}
args="$@"
while [ -n "$1" ] ; do
    case "${1}" in
    "-b"  | "--build" ) build=yes ;;        ### build rpm
    "-o"  | "--name") shift; name="$1" ;;   ### name for fake package
    "-r"  | "--requires") shift ; R="$1" ;; ### space separated list for Requires tags
    "-p"  | "--provides") shift ; P="$1" ;; ### space separated list for Provides tags
    "-l"  | "--links") shift ; L="$1" ;;    ### space separated list to create links in fomat target:link
    "-s"  | "--save" ) SAVE=yes ;;      ### do not remove buid dir
    "-h"  | "--help" ) HLP ;;           ### this help
    *)  echo "$(basename "$0"): invalid option ${1}"
        exit 1 ;;
    esac
shift
done

[ $name ] || name=fakerpm

echo "links: $L"
echo "requires: $R"
echo "provides: $P"

cat << EOF > ${name}.spec
Summary:        fake rpm package $name
Name:           $name
Version:        1
Release:        1
License:        GPLv3+
Group:          System/Base
BuildArch:  noarch
EOF

[ "$R" ] && for a in $R ; do
echo "Requires: $a" >> ${name}.spec
done

[ "$P" ] && for a in $P ; do
echo "Provides: $a" >> ${name}.spec
done

cat << EOF >> ${name}.spec
%description
Rpm package $name, built by mkfakerp: 
$0 "$args"
Needed to install enemy rpm package with non-native ROSA rpm names in the Requires tags.
EOF

if [ "$L" ] ; then
echo '%post' >> ${name}.spec
for a in $L ; do
    target=$(echo $a |cut -f1 -d ':')
    link=$(echo $a |cut -f2 -d ':')
    echo "ln -s $target $link" >> ${name}.spec
done
fi
echo "
%prep
%build
%install
" >> ${name}.spec

[ "$L" ] && for a in $L ; do
    link=$(echo $a |cut -f2 -d ':')
    echo "mkdir -p %{buildroot}$(dirname $link)" >> ${name}.spec
done

echo "%files" >> ${name}.spec

[ "$L" ] && for a in $L ; do
    echo "%ghost $(echo $a |cut -f2 -d ':')"  >> ${name}.spec
done

if [ "$build" ] ; then
    BUILDDIR=$(mktemp -d /tmp/fake-XXX)
    [ -d ${BUILDDIR}/bin ] && exit ${LINENO}
    mkdir -p ${BUILDDIR}/{BUILD,BUILDROOT,RPMS,SRPMS}
    rpmbuild -bb ${name}.spec --define="_sourcedir $BUILDDIR" --define="_topdir $BUILDDIR"
    if [ $(ls -1 "${BUILDDIR}"/RPMS/*/ |wc -l) -gt 0  ] ; then
        mv "${BUILDDIR}"/RPMS/*/* ./
    else
    echo "rpmbuild error :("
    fi
    if [ $SAVE ] ; then 
    echo "${BUILDDIR}"
    else
    rm -rf "${BUILDDIR}"
    fi
fi
