#!/usr/bin/python3

import os
import sys

def fix_installed(layers):
    installed = []
    for layer in layers[:-1]:
        try:
            with open(os.path.join(layer, 'lib/apk/db/installed'), 'r') as fd:
                buffer = []
                for line in fd:
                    if line.startswith('C:'):
                        buffer = ''.join(buffer)
                        if buffer not in installed:
                            installed.append(buffer)
                        buffer = []
                    buffer.append(line)
                buffer = ''.join(buffer)
                if buffer not in installed:
                    installed.append(buffer)
        except:
            continue
    os.makedirs(os.path.join(layers[-1], 'lib/apk/db'), 0o755, True)
    with open(os.path.join(layers[-1], 'lib/apk/db/installed'), 'w') as fd:
        fd.writelines(installed)

def fix_world(layers):
    world = []
    for layer in layers[:-1]:
        try:
            with open(os.path.join(layer, 'etc/apk/world'), 'r') as fd:
                for line in fd:
                    if line not in world:
                        world.append(line)
        except:
            continue
    os.makedirs(os.path.join(layers[-1], 'etc/apk'), 0o755, True)
    with open(os.path.join(layers[-1], 'etc/apk/world'), 'w') as fd:
        fd.writelines(world)

fix_installed(sys.argv[1:])
fix_world(sys.argv[1:])
