# -*- coding: utf-8 -*-
from setupdevhelpers import *

release_only = False

def update_package():
    list_package = ['git','build-essential','zlib1g-dev','binutils-dev','gcc','liblzma-dev','make']
    print('install %s' % ' '.join(list_package))
    install_apt(' '.join(list_package))
    tmpdir='/tmp'

    mkdirs('%s/ipxe' % tmpdir)
    run('git clone https://github.com/ipxe/ipxe.git %s/ipxe' % tmpdir)

    if release_only:
        hashgit = json.loads(wgets('https://api.github.com/repos/ipxe/ipxe/tags'))[0]['commit']['sha']
        run('git -C %s/ipxe reset --hard %s --' % (tmpdir,hashgit))

    print('custom ipxe')
    with open('%s/ipxe/src/config/console.h' % tmpdir,'r') as f:
        data = f.read()
    data = data.replace('#define	KEYBOARD_MAP	us','#define	KEYBOARD_MAP	dynamic')

    with open('%s/ipxe/src/config/console.h' % tmpdir,'w') as f:
        f.write(data)

    print('compile legacy ipxe')
    run('cd %s/ipxe/src ; make bin/undionly.kpxe' % tmpdir)
    run('cd %s/ipxe/src ; make bin/ipxe.kpxe' % tmpdir)
    print('compile uefi ipxe')
    run('cd %s/ipxe/src ; make bin-x86_64-efi/ipxe.efi' % tmpdir)
    print('compile uefi snponly')
    run('cd %s/ipxe/src ; make bin-x86_64-efi/snponly.efi' % tmpdir)

    pxe_folder = basedir
    filecopyto('%s/ipxe/src/bin/undionly.kpxe' % tmpdir,'%s/undionly.kpxe' % pxe_folder)
    filecopyto('%s/ipxe/src/bin/ipxe.kpxe' % tmpdir,'%s/ipxe.kpxe' % pxe_folder)
    filecopyto('%s/ipxe/src/bin-x86_64-efi/ipxe.efi' % tmpdir, '%s/ipxe.efi' % pxe_folder)
    filecopyto('%s/ipxe/src/bin-x86_64-efi/snponly.efi' % tmpdir, '%s/snponly.efi' % pxe_folder)

    version = "0.0.%s" % run(r"git -C  %s/ipxe rev-list --count master" % tmpdir).strip()
    hashgit = run("git -C  %s/ipxe rev-parse HEAD" % tmpdir).split("\n")[0]
    control.sources = 'https://github.com/ipxe/ipxe/commit/%s' %  hashgit
    control.version = "%s-%s" % (version, control.version.split("-", 1)[-1])
    control.save_control_to_wapt()