#!/usr/bin/python
#
# A simple script for deploying the artifacts of
# the current directory.
#

from __future__ import print_function

import glob
import os
import re
import sys
from subprocess import call
from subprocess import check_output

all_debs = sorted(glob.glob("*.deb"))
user = os.environ.get('BINTRAY_USER')
if user is None:
	sys.exit('Please specifiy the BINTRAY_USER env variable')

key = os.environ.get('BINTRAY_API_KEY')
if key is None:
	sys.exit('Please specify the BINTRAY_API_KEY env variable')

for deb in all_debs:
	# Check whether this deb should be released after all
	changelog_head = check_output("dpkg-deb --fsys-tarfile '{0}' | tar x --wildcards '*/changelogs*.gz' -O | gzip -dc | head -2".format(deb), shell=True)
	if 'UNRELEASED' in changelog_head:
		print('Skip uploading of {0} because it is marked as UNRELEASED.'.format(deb))
		continue

	deb_info = check_output(['dpkg', '--info', deb])

	m = re.search('Package: ([\w\.-]+)', deb_info)
	pkg = m.group(1)

	m = re.search('Version: ([\w\.-~]+)', deb_info)
	version = m.group(1)

	url = 'https://api.bintray.com/content/ontologizer/deb/' + pkg + '/' + version + '/' + deb + ';deb_distribution=unstable;deb_component=main;deb_architecture=all;publish=1'

	print('Uploading ' + deb);
	call(['curl', '-T', deb, '-u' + user + ':' + key, url])
