#!/usr/bin/env python3

# shell quoting sucks *so hard* that I switched to python.

# PostmarketOS comes with mkbootimg-osm0sis and unpackbootimg, which
# aren't *quite* inverses of each other. This script is a
# quick-and-dirty almost-inverse of unpackbootimg.

import sys
import os

[_exe, basefilename] = sys.argv

cmdline = ['mkbootimg-osm0sis']

for p in ['base', 'board', 'cmdline', 'hashtype',
          'kernel_offset', 'os_patch_level', 'os_version', 'pagesize',
          'ramdisk_offset', 'second_offset', 'tags_offset']:
    filename = basefilename + '-' + p
    try:
        with open(filename, 'rt') as f:
            param = f.read().strip()
    except FileNotFoundError:
        param = ''
    if param:
        cmdline.append('--' + p)
        cmdline.append(param)

cmdline = cmdline + ['--kernel', basefilename + '-zImage',
                     '--dt', basefilename + '-dt',
                     '--ramdisk', basefilename + '-ramdisk.gz',
                     '-o', basefilename]

os.execvp(cmdline[0], cmdline)
