#! /bin/bash

set -e

. ./pika-build-config.sh

VERSION="$PIKA_PACKAGE_VERSION"

echo "$PIKA_BUILD_ARCH" > pika-build-arch

# Get source code
if [[ "$PIKA_PACKAGE_NAME" == *-dmo ]];
then
	apt-get source "$PIKA_PACKAGE_NAME" -y
else
	apt-get source "$PIKA_PACKAGE_NAME=$VERSION" -y
fi

if [ "$PIKA_REBUILD" = true ]
then
    VERSION="$VERSION+$PIKA_REBUILD_VERSION"
fi

# Get build deps
#LOGNAME=root dh_make --createorig -y -l -p src-pkg-name_"$VERSION" || echo "dh-make: Ignoring Last Error"

# Enter build dir
cd $(find ./ -maxdepth 1 -name "$PIKA_PACKAGE_NAME*" -type d | head -1)

# DO PATCHING
if git clone --depth=1 https://git.pika-os.com/upstream-patches/"$PIKA_PACKAGE_NAME".git ../patches
then
	if [ -f ../patches/series ]
	then
		if cat ./debian/source/format | grep 'quilt'
		then
			cp -rvf ../patches/patches ./debian/
			cat ../patches/series >> ./debian/patches/series
		else
			for i in $(cat ../patches/series)
			do
				echo "Applying Patch: $i"
				patch -Np1 -i ../patches/patches/$i || bash -c "echo "Applying Patch $i Failed!" && exit 2"
			done
		fi
	fi
	if [ -f ../patches/native-series ]
	then
		for i in $(cat ../patches/native-series)
		do
			echo "Applying Patch: $i"
			patch -Np1 -i ../patches/patches/$i || bash -c "echo "Applying Patch $i Failed!" && exit 2"
		done
	fi
fi

# Reversion changelog
if [ "$PIKA_REBUILD" = true ]
then
	CHANGELOG_DATE=$(date '+%a, %d %b %Y %H:%M:%S %z')
	CHANGELOG_APPEND="$PIKA_PACKAGE_NAME ($VERSION) pika; urgency=medium\n\n  *  PikaOS 4 Rebuild.\n\n -- Ward Nakchbandi <hotrod.master@hotmail.com>  $CHANGELOG_DATE\n"
	sed -i "1s/^/$CHANGELOG_APPEND\n/" debian/changelog
	if [ -f debian/control ]
	then
		sed -i "s#source:Version#binary:Version#g" debian/control
	fi
	if [ -f debian/control.in ]
	then
		sed -i "s#source:Version#binary:Version#g" debian/control.in
	fi
fi

# Get build deps
apt-get build-dep ./ -y

# Build Binary Packages
dpkg-buildpackage --no-sign

# Move the debs to output
cd ../
mkdir -p ./output
mv ./*.deb ./output/