#!/usr/bin/python3
# encoding=utf-8
#
# Copyright © 2023 Alexandre Detiste <alexandre@detiste.be>
# SPDX-License-Identifier: FSFAP

import os
import subprocess
import time

import distro_info

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

DH_VERSIONS = {
    'xenial': 9,
    'jammy': 13,
    'kinetic': 13,
    'lunar': 13,
}

subprocess.check_call(['git', 'checkout', 'debian/changelog'],
                       cwd = GIT)
subprocess.check_call(['git', 'checkout', 'debian/control'],
                       cwd = GIT)

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', 'experimental'), 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+')

lts = distro_info.UbuntuDistroInfo().lts()
current = distro_info.UbuntuDistroInfo().stable()

releases = sorted(set([lts, current]))
print('RELEASES:', releases)

with open('debian/control', 'r') as compat:
    for line in compat:
        if 'debhelper-compat' in line:
            current_debhelper =  int(line.split('(')[1].strip(' =),\n'))
            break

for release in sorted(releases):
    supported_debhelper = DH_VERSIONS.get(release, current_debhelper)
    backported = set()

    if supported_debhelper < current_debhelper:
        backported.add('control')
        build_dep = 'debhelper-compat ( = %d)' %  supported_debhelper
        subprocess.check_call(['sed', '-i',
                               's/\ *debhelper-compat.*/ ' + build_dep + ',/',
                               'debian/control'],
                              cwd = GIT)

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

    subprocess.check_call(['debuild', '-S', '-sa'],cwd = GIT)
    subprocess.check_call(['dput', 'my-ppa',
                           'gargoyle-free_%s_source.changes' % snapshot],
                           cwd = BASE)

    subprocess.check_call(['git', 'checkout', 'debian/changelog'],
                          cwd = GIT)

    for item in backported:
        subprocess.check_call(['git', 'checkout', 'debian/' + item],
                               cwd = GIT)
    for file in ('.dsc',
                 '_source.build',
                 '_source.changes',
                 '_source.my-ppa.upload'):
        subprocess.check_call(['rm', '-v',
                               'gargoyle-free_%s%s' % (snapshot, file)],
                              cwd = BASE)
