#!/bin/bash

#= Fedora 29+ amd64 .rpm

set -o errexit
set -o xtrace

# Move to source directory
pushd ${SOURCE_DIR}

if [[ ${IS_DOCKER} == YES ]]; then
    # Remove BuildRequires for dotnet, since it's installed manually
    pushd fedora

    cp -a jellyfin.spec /tmp/spec.orig
    sed -i 's/BuildRequires:  dotnet/# BuildRequires:  dotnet/' jellyfin.spec

    popd
fi

# Modify changelog to unstable configuration if IS_UNSTABLE
if [[ ${IS_UNSTABLE} == 'yes' ]]; then
    pushd fedora

    PR_ID=$( git log --grep 'Merge pull request' --oneline --single-worktree --first-parent | head -1 | grep --color=none -Eo '#[0-9]+' | tr -d '#' )

    sed -i "s/Version:.*/Version:        ${BUILD_ID}/" jellyfin.spec
    sed -i "/%changelog/q" jellyfin.spec

    cat <<EOF >>jellyfin.spec
* $( LANG=C date '+%a %b %d %Y' ) Jellyfin Packaging Team <packaging@jellyfin.org>
- Jellyfin Server unstable build ${BUILD_ID} for merged PR #${PR_ID}
EOF
    popd
fi

# Build RPM
make -f fedora/Makefile srpm outdir=/root/rpmbuild/SRPMS
rpmbuild -rb /root/rpmbuild/SRPMS/jellyfin-*.src.rpm

# Move the artifacts out
mv /root/rpmbuild/RPMS/x86_64/jellyfin-*.rpm /root/rpmbuild/SRPMS/jellyfin-*.src.rpm ${ARTIFACT_DIR}/

if [[ ${IS_DOCKER} == YES ]]; then
    chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
fi

rm -f fedora/jellyfin*.tar.gz

if [[ ${IS_DOCKER} == YES ]]; then
    pushd fedora

    cp -a /tmp/spec.orig jellyfin.spec
    chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}

    popd
fi

popd
