#!/usr/bin/python3

import os
import re
import sys
import subprocess
import fileinput

def update_version():
    if os.path.isfile ('VERSION'):
        with open ('VERSION', 'r') as version_file:
            version = version_file.read().strip()

        pattern = r'[0-9]*\.[0-9]*\.[0-9]*'
        matches = re.findall (pattern, version)
        win_version = matches[0]

        with fileinput.FileInput ('about-dialog.ui', inplace=True) as file:
            for line in file:
                new = re.sub (r'Version [^<]*', 'Version {}'.format(version), line)
                print (new, end='')

        with fileinput.FileInput ('opengnsys/__init__.py', inplace=True) as file:
            for line in file:
                new = re.sub (r'VERSION=.*', "VERSION='{}'".format(version), line)
                print (new, end='')

        with open ('../windows/VERSION', 'w') as outfile:
            outfile.write (win_version + '\n')

    else:
        print ('VERSION: No such file or directory')
        sys.exit (1)

def process_ui():
    subprocess.run (['pyuic6', 'about-dialog.ui',   '-o', 'about_dialog_ui.py',   '-x'])
    subprocess.run (['pyuic6', 'message-dialog.ui', '-o', 'message_dialog_ui.py', '-x'])

if __name__ == "__main__":
    os.chdir (os.path.dirname (os.path.abspath (__file__)))
    update_version()
    process_ui()
