#!/usr/bin/python3
# encoding=utf-8
#
# Copyright © 2015 Alexandre Detiste <alexandre@detiste.be>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# You can find the GPL license text on a Debian system under
# /usr/share/common-licenses/GPL-2.

import os
import subprocess
import sys
import time

#BASE = '/home/tchet/git'
#GDP = os.path.join(BASE, 'game-data-packager')

GDP = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
BASE = os.path.dirname(GDP)

subprocess.check_call(['rm', '-rvf', 'ref.zip'],
                       cwd = GDP)
subprocess.check_call(['git', 'checkout', 'debian/changelog'],
                       cwd = GDP)
subprocess.check_call(['git', 'checkout', 'debian/compat'],
                       cwd = GDP)
subprocess.check_call(['git', 'checkout', 'debian/control'],
                       cwd = GDP)

from debian.changelog import Changelog
with open('debian/changelog', encoding='utf-8') as log:
    cl = Changelog(log, strict=False)

assert cl.distributions in ('unstable','UNRELEASED'), cl.distributions

if cl.distributions == 'unstable':
   build_type = 'Backport to PPA'
   build_number = 'release+'
else:
   build_type = 'Git snapshot'
   build_number = time.strftime('git%Y%m%d+')

with open('/usr/share/distro-info/ubuntu.csv', 'r') as data:
    for line in data.readlines():
       version, _, release, _, date, _ = line.split(',', 5)
       if version == 'version':
          continue
       if len(sys.argv) > 1 and sys.argv[1] == release:
          current = release
          lts = release
          break
       if time.strptime(date, '%Y-%m-%d') > time.localtime():
          continue
       current = release
       if 'LTS' in version:
          lts = release

releases = sorted(set([lts, current]))

with open('debian/compat', 'r') as compat:
    current_debhelper =  int(compat.readline().strip())

for release in sorted(releases):

    supported_debhelper = {
            'xenial': 9,
            }.get(release, current_debhelper)
    BACKPORT = supported_debhelper < current_debhelper

    if BACKPORT:
        with open('debian/compat', 'w') as compat:
            compat.write('%d\n' % supported_debhelper)
        build_dep = 'debhelper  (>= %d~)' %  supported_debhelper
        if supported_debhelper == 9:
            build_dep = build_dep + ',' + 'dh-systemd'
        subprocess.check_call(['sed', '-i',
                               's/\ *debhelper.*/ ' + build_dep + ',/',
                               'debian/control'],
                              cwd = GDP)

    snapshot = str(cl.version) + '~' + build_number + release
    subprocess.check_call(['dch', '-b',
                           '-D', release,
                           '-v', snapshot,
                           build_type],
                          cwd = GDP)

    # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=853795
    # "Ubuntu ppa's (launchpad) do not support .buildinfo files and reject them"
    subprocess.check_call(['debuild', '-S', '-i', '--buildinfo-option=-O'],cwd = GDP)
    subprocess.check_call(['dput', 'my-ppa',
                           'game-data-packager_%s_source.changes' % snapshot],
                           cwd = BASE)

    subprocess.check_call(['git', 'checkout', 'debian/changelog'],
                          cwd = GDP)
    if BACKPORT:
        subprocess.check_call(['git', 'checkout', 'debian/compat'],
                               cwd = GDP)
        subprocess.check_call(['git', 'checkout', 'debian/control'],
                               cwd = GDP)

    for file in ('.tar.xz',
                 '.dsc',
                 '_source.build',
                 '_source.changes',
                 '_source.my-ppa.upload'):
        subprocess.check_call(['rm', '-v',
                               'game-data-packager_%s%s' % (snapshot, file)],
                              cwd = BASE)
