#!/usr/bin/python

# Script to be run in git branch of debian/ packaging,
# it adds a ppa version number to the changelog
# then downloads the .orig
# then builds the source package ready for upload to the PPA using git-buildpackage
# Jonathan Riddell 2014-10-01
# may be copied under GNU GPL version 2 or later

import argparse
from distro_info import UbuntuDistroInfo
import os.path
import subprocess
import sys
from debian import changelog

parser = argparse.ArgumentParser(description="Build source packages for PPAs.")
#parser.add_argument("-d", "--dist", default=UbuntuDistroInfo().devel(), help="Distribution name (default: current development release)")
parser.add_argument("-d", "--dist", default="xenial", help="Distribution name (default: current development release)")
parser.add_argument("-s", "--suffix", default=1, help="PPA version suffix, i.e. ~ppaX (default: 1)")
parser.add_argument("-y", "--distversion", default="16.04", help="distro version number")
parser.add_argument("options", nargs="*", help="debuild options")

args = parser.parse_args()

if not os.path.exists("debian/changelog"):
    print >> sys.stderr, "Error: Not a Debian package."
    sys.exit(1)

f = open("debian/changelog", "r")
lines = f.readlines()
f.close()

if not "UNRELEASED" in lines[0]:
    print >> sys.stderr, "Error: Distribution is not \"UNRELEASED\"."
    sys.exit(1)

if "ppa" in lines[0]:
    print >> sys.stderr, "Error: Version contains \"ppa\"."
    sys.exit(1)

if not os.path.exists('../build-area/'):
    os.makedirs('../build-area/')

d = changelog.Changelog(open('debian/changelog'))
name = d.get_package()
version = d.get_version().upstream_version
tarname = "%s_%s.orig.tar.xz" % (name, version)

#subprocess.call(["apt-get", "source", ("%s" % name)])
subprocess.call(["uscan", "--download-current-version", "--destdir=../build-area"])

if os.path.isfile("../%s" % tarname) and not os.path.isfile("../build-area/%s" % tarname):
    os.symlink("../%s" % tarname, "../build-area/%s" % tarname)

if not os.path.isfile("../build-area/%s" % tarname):
    print "Didn't manage to find %s anywhere in an appropriate version, put one in build-area, kthxbai" % tarname
    sys.exit(1)

version = str(d.get_version())
version += "~ubuntu" + str(args.distversion) + "~ppa" + str(args.suffix)

application = ["gbp", "buildpackage",
                "--git-export-dir=../build-area",
                "--git-tarball-dir=../build-area",
                "--git-no-create-orig",
                "--git-overlay",
                "--git-ignore-branch",
                "--git-ignore-new",
                "--git-prebuild=dch -b -v " + version + " PPA build; dch -D " + args.dist + " -r PPA build",
                "-S"]
if args.suffix > 1:
    application += ["-sd"]
else:
    application += ["-sa"]

application += args.options
print "calling: " + " ".join(application)
subprocess.call(application)

# kate: space-indent on; indent-width 4; replace-tabs on; indent-mode python; remove-trailing-space on;
