#!/bin/sh

PLAYGROUND_DIR=@CMAKE_BINARY_DIR@/packaging/pkgbuild/playground;
BUILD_ROOT_DIR=${PLAYGROUND_DIR}/build_root
BLOOM_INSTALLATION_PREFIX=@BLOOM_INSTALLATION_PREFIX@/
BLOOM_INSTALLATION_DIR=${BUILD_ROOT_DIR}/${BLOOM_INSTALLATION_PREFIX}
BLOOM_PACKAGE_PATH=@CMAKE_BINARY_DIR@/packaging/@BLOOM_PACKAGE_FILE_NAME@.pkg.tar.gz

if [ ! -f @CMAKE_BINARY_DIR@/bin/bloom ]; then
    echo "Build files not found. Did you forget to build?"
    exit 1;
fi

echo "Preparing playground directory...";
rm -fr ${PLAYGROUND_DIR};

mkdir -p ${PLAYGROUND_DIR};
mkdir -p ${BUILD_ROOT_DIR};
mkdir -p ${BLOOM_INSTALLATION_DIR};
mkdir -p ${BLOOM_INSTALLATION_DIR}/bin;

mkdir -p ${BUILD_ROOT_DIR}/usr/lib/udev/rules.d/;
mkdir -p ${BUILD_ROOT_DIR}/usr/bin/;

echo "Copying PKGBUILD control file...";
cp -a @CMAKE_BINARY_DIR@/packaging/pkgbuild/PKGBUILD ${PLAYGROUND_DIR}/;

echo "Copying Bloom binary...";
cp -a @CMAKE_BINARY_DIR@/bin/bloom ${BLOOM_INSTALLATION_DIR}/bin/;

echo "Copying Bloom invocation script...";
cp -a @CMAKE_BINARY_DIR@/packaging/bloom.sh ${BLOOM_INSTALLATION_DIR}/bin/;

echo "Copying resources...";
cp -a @CMAKE_BINARY_DIR@/resources ${BLOOM_INSTALLATION_DIR}/;
cp -a @CMAKE_CURRENT_SOURCE_DIR@/build/distributed/fonts ${BLOOM_INSTALLATION_DIR}/resources/;

echo "Copying distributed binaries...";
cp -a @CMAKE_CURRENT_SOURCE_DIR@/build/distributed/bin/lib ${BLOOM_INSTALLATION_DIR}/;
cp -a @CMAKE_CURRENT_SOURCE_DIR@/build/distributed/bin/plugins ${BLOOM_INSTALLATION_DIR}/;

# We don't ship libstdc++ shared objects in Arch packages - the package manager will install the one we need
rm -f ${BLOOM_INSTALLATION_DIR}/lib/libstdc++.so.*;

echo "Copying udev rules...";
cp -a @CMAKE_CURRENT_SOURCE_DIR@/build/distributed/udevrules/99-bloom.rules ${BUILD_ROOT_DIR}/usr/lib/udev/rules.d/;

echo "Adjusting permissions...";
chmod u=rwx,g=rx,o=rx -R ${BLOOM_INSTALLATION_DIR}/bin/;
chmod u=rwx,g=rx,o=rx -R ${BLOOM_INSTALLATION_DIR}/lib/;
chmod u=rwx,g=rx,o=rx -R ${BLOOM_INSTALLATION_DIR}/plugins/;

chmod u=rwX,g=rX,o=rX -R ${BLOOM_INSTALLATION_DIR}/resources/;

chmod u=rw,g=r,o=r ${BUILD_ROOT_DIR}/usr/lib/udev/rules.d/99-bloom.rules;

echo "Creating symbolic link for Bloom's invocation script..."
ln -s -f ${BLOOM_INSTALLATION_PREFIX}./bin/bloom.sh ${BUILD_ROOT_DIR}/usr/bin/bloom;

echo "Building Arch package...";
cd ${PLAYGROUND_DIR};
makepkg;
mv ./@BLOOM_PACKAGE_NAME_LOWER@-@CMAKE_PROJECT_VERSION@-1-x86_64.pkg.tar.gz ${BLOOM_PACKAGE_PATH};
