#!/bin/sh

#set -ex

descompress() {
	st_extension=$(echo "$1" |  grep -oE "\w*$")
	case "${st_extension}" in
		"xz")
			echo "tar Jxf"
		;;
		"gz")
			echo "tar zxf"
		;;
		"bz2")
			echo "tar jxf"
		;;
		*)
			echo "Invalid Package Layout"
			exit 1
		;;
	esac
}

st_base_path=${PWD}
echo ${st_base_path}

if [ -z $1 ]; then
	echo "Please insert package name: "
	exit 1
else
	st_package=$1
	echo "Importing package ${st_package} ..."
fi

tx_description=$(apt show ${st_package} 2> /dev/null)
if [ -z "${tx_description}" ]; then
	echo "Cannot found package: ${st_package}"
	exit 1
fi

st_repository="git@gitlab.comtex.com.br:multivisos/packages/binary/amd64/$1.git"
bo_package=$(git ls-remote -q -h $st_repository 2> /dev/null | wc -l) 
if [ $bo_package -ne 0 ]; then
	echo "There is the package"
	exit 1;
fi 

mkdir -p "${st_base_path}/${st_package}"
cd "${st_base_path}/${st_package}"

apt download ${st_package}
st_file=$(ls -1 | grep *.deb)
mv "${st_file}" "${st_package}.deb"

ar -x "${st_package}.deb"
rm -f debian-binary "${st_package}.deb"
mkdir -p src/DEBIAN/

st_file=$(ls -1 | grep control.tar.*)
st_command=$(descompress "${st_file}")
${st_command} "${st_base_path}/${st_package}/${st_file}" -C "${st_base_path}/${st_package}/src/DEBIAN/"
rm -fr "${st_base_path}/${st_package}/${st_file}"

st_file=$(ls -1 | grep data.tar.*)
st_command=$(descompress "${st_file}")
${st_command} "${st_base_path}/${st_package}/${st_file}" -C "${st_base_path}/${st_package}/src/"
rm -fr "${st_base_path}/${st_package}/${st_file}"

sed -i 's/^Maintainer:.*/Maintainer: Multivis Development Team <devteams@multivis.com>/' "${st_base_path}/${st_package}/src/DEBIAN/control"
st_file=$(cat "${st_base_path}/${st_package}/src/DEBIAN/control")
st_description=$(echo ${st_file} |  grep "Description:" | sed -r 's/Description: //')
echo "# ${st_package}\n${st_description}" > "${st_file}"

st_file="${st_base_path}/${st_package}/make.sh"
wget -O - http://repo.multiviscloud.com/installer/scripts/mkpack.sh > "${st_file}"
chmod 755 "${st_file}"

git init
git add -A
git commit -m "Imported from Debian Buster"
git remote add origin "${st_repository}"
git push --set-upstream origin master

"${st_file}"

rm -fr "${st_base_path}/${st_package}"