#!/usr/bin/env python

import os

SCHEMA_DIR = os.path.dirname(__file__)
MIGRATIONS_DIR = os.path.join(SCHEMA_DIR, 'migrations')

MIGRATION_FILES = [filename for filename in os.listdir(MIGRATIONS_DIR) if
                   os.path.isfile(os.path.join(MIGRATIONS_DIR, filename))]


def migration_file_name_to_int(name):
    print('Filename {}'.format(name))
    name = name.split('-')[0]
    return int(name[:-1].lstrip('0') + name[-1])


def read_file(directory, path):
    with open(os.path.join(directory, path), 'r') as f:
        return f.read()


MIGRATION_DATA = [
    (migration_file_name_to_int(migration_file), read_file(MIGRATIONS_DIR, migration_file)) for
    migration_file in MIGRATION_FILES]
MIGRATION_DATA.sort()

SCHEMA_TEMPLATE = '''
""" This file is auto-generated by res/schema/embed.py - DO NOT MODIFY THIS FILE MANUALLY """

CURRENT_SCHEMA = """{current_schema}"""
"""Current schema of the leapp database"""

MIGRATIONS = [
    {migrations}
]
"""Migrations for previous versions of the leapp database"""
'''

with open(os.path.join(SCHEMA_DIR, 'schemas.py'), 'w') as f:
    f.write(SCHEMA_TEMPLATE.format(
        current_schema=read_file(SCHEMA_DIR, 'audit-layout.sql'),
        migrations=',\n    '.join('({}, """{}""")'.format(*entry) for entry in MIGRATION_DATA)))
