#!/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 :)
#  Written May 06, 2020 - Terry Neve

ARCH=$(uname -m)
DIST=$(rpm -E %distribution | tr A-Z a-z | sed "s| |_|g")
DISTARCH="64bit"
TOPDIR=$HOME/src
RPMMACS=$HOME/.rpmmacros
APTLINE="rpm file:${TOPDIR}/apt/ ${DIST}/${DISTARCH} noarch ${ARCH}"

# Build the rpmbuild tree
mkdir -p $TOPDIR/{apt/$DIST/$DISTARCH/base,rpm/{BUILD,SOURCES,SPECS,SRPMS,RPMS/{noarch,$ARCH}},tmp}

# Build the local repository tree
pushd $TOPDIR/apt/$DIST/$DISTARCH &>/dev/null
for i in $(ls $TOPDIR/rpm/RPMS); do
    [ -d "RPMS.$i" ] || ln -sf $TOPDIR/rpm/RPMS/$i RPMS.$i
done
popd &>/dev/null

# 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 a modified sources.list with local repo included
awk -v var="$APTLINE" '/^rpm/{print var}1' /etc/apt/sources.list >$TOPDIR/tmp/sources.list

echo "An updated sources.list has been saved in $TOPDIR/tmp"
read -p "Do you want to overwrite your current /etc/apt/sources.list (will require root password) ? " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    cp -p /etc/apt/sources.list $TOPDIR/tmp/sources.list.orig
    su -c "cp $TOPDIR/tmp/sources.list /etc/apt/sources.list"
fi
