#!/usr/bin/env python3
# NOTE: PYTHONUNBUFFERED is set in the entrypoint for unbuffered output
#
# An operation that mutates a build by generating an OpenStack image.

import os
import sys
import json
import shutil
import argparse

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from cosalib.builds import Builds
from cosalib.cmdlib import run_verbose, write_json, sha256sum_file, get_basearch

# Parse args and dispatch
parser = argparse.ArgumentParser()
parser.add_argument("--build", help="Build ID")
args = parser.parse_args()

# Identify the builds and target the latest build if none provided
builds = Builds()
if not args.build:
    args.build = builds.get_latest()
print(f"Targeting build: {args.build}")

builddir = builds.get_build_dir(args.build)
buildmeta_path = os.path.join(builddir, 'meta.json')
with open(buildmeta_path) as f:
    buildmeta = json.load(f)

basearch = get_basearch()
base_name = buildmeta['name']
img_prefix = f'{base_name}-{args.build}'
openstack_name = f'{img_prefix}-openstack.{basearch}.qcow2'

tmpdir = 'tmp/buildpost-openstack'
if os.path.isdir(tmpdir):
    shutil.rmtree(tmpdir)
os.mkdir(tmpdir)


def generate_openstack():
    buildmeta_images = buildmeta['images']
    img_qemu = os.path.join(builddir, buildmeta_images['qemu']['path'])
    tmp_img_openstack = os.path.join(tmpdir, openstack_name)
    run_verbose(['/usr/lib/coreos-assembler/gf-platformid',
                 img_qemu, tmp_img_openstack, 'openstack'])
    checksum = sha256sum_file(tmp_img_openstack)
    size = os.path.getsize(tmp_img_openstack)
    buildmeta_images['openstack'] = {
        'path': openstack_name,
        'sha256': checksum,
        'size': size
    }
    os.rename(tmp_img_openstack, f"{builddir}/{openstack_name}")
    write_json(buildmeta_path, buildmeta)
    print(f"Updated: {buildmeta_path}")


# Do it!
generate_openstack()
