#! /bin/bash

set -e

. ./pika-build-config.sh

VERSION="$PIKA_PACKAGE_VERSION"

echo "$PIKA_BUILD_ARCH" > pika-build-arch

if [[ $PIKA_BUILD_ARCH == "amd64-v3" ]]
then
	export PIKA_BIN_ARCH="amd64"
fi

if [[ $PIKA_BUILD_ARCH == "i386" ]]
then
	export PIKA_BIN_ARCH="i386"
fi

apt-get update -y

mkdir -p ./output

# 
BIN_PACKAGE_NAME_LIST=$(apt showsrc "$PIKA_PACKAGE_NAME" | grep -E "^Binary:" | cut -d":" -f2- | sed 's/\,/\n/g' | sed 's/\ /\n/g' | sed '/^$/d' | sort -u)
for bin_pkg in $BIN_PACKAGE_NAME_LIST
do
	BIN_VERSION=$(apt show $bin_pkg:$PIKA_BIN_ARCH 2>&1 | grep Version: | head -n1 | cut -f2- -d":" | cut -f2- -d":" | tr -d ' ')
	TARGET_VERSION=$(echo $BIN_VERSION | sed 's/\+b.*//')
	if apt download -y $bin_pkg:$PIKA_BIN_ARCH
	then
		if [[ $BIN_VERSION == $TARGET_VERSION ]]
		then
			mv -vf ./*.deb ./output/ 
		else
			for i in ./*.deb
			do
				mkdir $i-tmp
				dpkg-deb -R $i $i-tmp
				sed -i "s#$BIN_VERSION#$TARGET_VERSION#g" $i-tmp/DEBIAN/control
				sed -i -E '/^Depends:/ s/\(\=[^ ]*/(>=/g; s/\+b[0-9]+//g' $i-tmp/DEBIAN/control
				dpkg-deb -b $i-tmp $i-fixed_$PIKA_BIN_ARCH.deb
				mv -vf ./*-fixed_$PIKA_BIN_ARCH.deb ./output/
				rm -rf ./*.deb
			done
		fi
	else
		echo "Maybe Error: $bin_pkg doesn't exist in $PIKA_BIN_ARCH"
	fi
done