#!/bin/bash

#  Set up user environment for PCLinuxOS packaging.
#  Simpler than mkrepo as it doesn't need Zenity or Yad and doesn't ask difficult questions :)
#
#  Revisions:
#       20220218.01  Initial working version
#       20260920.01  Create /etc/repo.d/local.repo for DNF instead of adding
#                    an apt sources.list line

ARCH=$(uname -m)
TOPDIR=$HOME/src
RPMMACS=$HOME/.rpmmacros
REPODIR=/etc/repo.d
REPOFILE=$REPODIR/local.repo
NEWREPO=$TOPDIR/tmp/local.repo

# Build the rpmbuild tree.  The RPMS folders double as the local DNF repo,
# so there is no separate repository tree to maintain.
mkdir -p $TOPDIR/{rpm/{BUILD,SOURCES,SPECS,SRPMS,RPMS/{noarch,$ARCH}},tmp}

# Create .rpmmacros
if [ -f $RPMMACS ]; then
    mv -f --backup=t $RPMMACS ${RPMMACS}.old &>/dev/null
fi
cat > $RPMMACS <<EOF
%_topdir        ${TOPDIR}/rpm
%_tmppath       ${TOPDIR}/tmp
%distribution   PCLinuxOS
%distsuffix     $USER
%vendor         PCLinuxOS
EOF

# Create the local repo definition, one section per RPMS folder
: > $NEWREPO
for i in $(ls $TOPDIR/rpm/RPMS); do
    cat >> $NEWREPO <<EOF
[local-$i]
name="Local $i RPMs"
baseurl=${TOPDIR}/rpm/RPMS/$i
gpgcheck=0
type=rpm-md
enabled=1

EOF
done

echo "A local repo definition has been saved in $NEWREPO"

if [ ! -d $REPODIR ]; then
    echo "Warning: $REPODIR does not exist - is DNF installed?"
    exit 1
fi

if [ -f $REPOFILE ]; then
    if diff -q $REPOFILE $NEWREPO &>/dev/null; then
        echo "$REPOFILE is already up to date."
        exit 0
    fi
    echo
    echo "Differences between $REPOFILE (<) and the new file (>):"
    diff $REPOFILE $NEWREPO
    echo
fi

read -p "Do you want to install it as $REPOFILE (will require root password) ? " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    [ -f $REPOFILE ] && cp -p $REPOFILE $TOPDIR/tmp/local.repo.orig
    su -c "cp $NEWREPO $REPOFILE"
    echo "Run crepo once you have built a package, to index the local repo."
fi
