#!/bin/bash

st_package_name=$1
if [ -z $st_package_name ]; then
	echo "Please insert package name: "
        exit 1
fi
echo "Building package ${st_package_name}"
#st_branch=$(git rev-parse --abbrev-ref HEAD)
st_package_name=$(basename "$st_package_name")
#st_package_name=$(echo $st_package_name | grep -Po '.*(?=\.)')
in_special=$(echo $st_package_name | grep -Po '^\.' | wc -l)
#if [ $in_special -eq 0 ]; then
	st_file="${st_package_name}.deb"
echo "File: $st_file" 
#else
#	st_file=$(echo "${st_package_name:1}" | sed 's/\./=/g')
#	st_file=$(echo "${st_file}" | base64 --decode)
#	st_file="${st_file}.deb"
#fi
st_path=$(readlink -f "$0")
st_path=$(dirname "$st_path")
#if [ "$st_branch" = 'unstable' ]; then
#	st_build=$(date +%s)
#	st_version=$(cat ./src/DEBIAN/control | grep -e 'Version:.*' | awk '{ print $2 }' | grep -oe "^[0-9]*\.[0-9]*")
#	st_version="$st_version.$st_build"
#	sed -i "s/Version:.*/Version: $st_version/g" $st_path/src/DEBIAN/control
#fi
echo "Creating package $st_file ..."
st_error="$(dpkg-deb --root-owner-group --build $st_path/src $st_path/$st_file 2> /dev/stdout > /dev/null)"
if [ -n "$st_error" ]; then
	echo $st_error
	exit 3
fi
echo "Created package"
echo "Signing package ..."
st_error="$(sudo dpkg-sig -s orig $st_path/$st_file 2> /dev/stdout > /dev/null)"
if [ -n "$st_error" ]; then
	echo $st_error
	exit 4
fi
echo "Signed package ${st_path/$st_file}"
scp -P2229 "$st_path/$st_file" comtex@repo.multiviscloud.com:/home/comtex/delta_packages/
ssh -p2229 comtex@repo.multiviscloud.com /home/comtex/scripts/includeMultivisOSDelta.sh delta/main /home/comtex/delta_packages/$st_file
