# current version adapted from https://gitlab.com/archlinux-packages-johnth/xen/tree/xen-4.10

# Maintainer (AUR): John Thomson <aur.xen at j0aur.mm.st>
# Contributor (Arch): David Sutton <kantras - gmail.com>
# Contributor (Arch): Shanmu Thiagaraja <sthiagaraja+AUR@prshanmu.com>
# Contributor (Arch): Limao Luo
# Contributor (Arch): Luceo
# Contributor (Arch): Revellion
# Contributor: André Silva <emulatorman@hyperbola.info>
# Contributor: Márcio Silva <coadde@hyperbola.info>
# Contributor: Isaac David <isacdaavid@at@isacdaavid@dot@info>

#linux-4.7 EFI boot panic issue (patch linux)
#http://lkml.iu.edu/hypermail/linux/kernel/1608.2/03448.html

_build_stubdom="${build_stubdom:-false}"
_system_seabios="${system_seabios:-false}"
_build_debug="${build_debug:-false}"
_build_livepatch="${build_livepatch:-false}"

## use _build_stubdom=true to build xen with stubdom
## use _system_seabios=true to use system seabios
## this bios file is slightly different to the xen seabios
## /usr/share/qemu/bios-256k.bin uses CONFIG_ROM_SIZE=256, and newer seabios
## can force use this file through vm.cfg bios_path_override='/usr/share/qemu/bios-256k.bin'
## use _build_debug=true to compile Xen with debug options
## use _build_livepatch=true to compile Xen with livepatch support

#_build_stubdom=true
#_system_seabios=true
#_build_debug=true
#_build_livepatch=true

pkgbase=xen
pkgname=(xen{,-docs,-syms})
_pkgname=xen
pkgver=4.10.0
_pkgver=${pkgver/rc/-rc}
pkgrel=1
pkgdesc='Virtual Machine Hypervisor & Tools (Parabola rebranded)'
arch=(x86_64 armv7h)
depends=(
    bridge-utils
    curl
    gnutls
    iproute2
    libaio
    libcacard
    libcap-ng
    libiscsi
    libnl
    libpng
    lzo
    pciutils
    python2
    sdl
    spice
    systemd
    usbredir
    yajl
    # seabios ovmf qemu
)
[[ "$CARCH" == 'x86_64' ]] && depends+=(
    lib32-glibc
)
[[ "$CARCH" == *'arm'* ]] && depends+=(
    dtc-overlay
)
[[ "$_system_seabios" == true ]] && depends+=(
    seabios
)
url='http://www.xenproject.org/'
license=('GPL2')
makedepends=(
    cmake
    figlet
    git
    markdown
    nasm
    ocaml-findlib
    spice-protocol
    wget
)
[[ "$CARCH" == 'x86_64' ]] && makedepends+=(
    bin86
    dev86
    gcc-multilib
    iasl
)
[[ "$CARCH" == 'i686' ]] && makedepends+=(
    bin86
    dev86
    iasl
)

## For building Xen EFI boot file.
## mingw-w64-binutils only needed if 
## binutils not built with --enable-targets=x86_64-pep 
_binutils_efi=false

if [[ "$CARCH" == 'x86_64' ]]; then
    if which ld 2>&1 > /dev/null; then
        _binutils_emulations="$(ld -V)"
        if [[ "$_binutils_emulations" == *'i386pep'* ]]; then
            _binutils_efi=true
            msg '#ld has efi support'
        else
            makedepends+=(
                mingw-w64-binutils
            )
            msg '#ld does not have efi support, using mingw'
        fi
    else
        true
    fi
fi


options=(!buildflags !strip)
changelog=ChangeLog

##SeaBIOS & OVMF tags are in src/xen-*/tools/Config.mk
##grep -rE '_(REVISION|VERSION|TAG)( \?| :){0,1}=' src/xen**/{Config.mk,stubdom/configure,tools/firmware/etherboot/Makefile}
_git_tag_seabios='#tag=rel-1.10.2'
_git_tag_ovmf='#tag=947f3737abf65fda63f3ffd97fddfa6986986868'
_git_tag_ipxe='356f6c1b64d7a97746d1816cef8ca22bdd8d0b5d'

if [[ "$_build_stubdom" == true ]]; then
    if [[ "$CARCH" == *'arm'* ]]; then
        echo '####Compile settings error:'
        echo "#cannot build stubdom for $CARCH"
        _build_stubdom=false
    fi
fi

source=(
    "https://downloads.xenproject.org/release/$_pkgname/$_pkgver/$_pkgname-$_pkgver.tar.gz"{,.sig}
    "http://xenbits.xen.org/xen-extfiles/ipxe-git-$_git_tag_ipxe.tar.gz"

    'seabios'::"git://xenbits.xen.org/seabios.git$_git_tag_seabios"
    'ovmf'::"git://xenbits.xen.org/ovmf.git$_git_tag_ovmf"
    ##HTTP access
    #'seabios'::"git+http://xenbits.xen.org/git-http/seabios.git$_git_tag_seabios"

    ## Compile patches
    ati-passthrough.patch
    patch-ovmf-use-python2.patch

    ## Files
    xen.install
    21_linux_xen_multiboot_arch
    efi-xen.cfg
    "tmpfiles.d-$_pkgname.conf"

    ## XSA patches
    https://xenbits.xen.org/xsa/xsa253.patch
)

if [[ "$_build_stubdom" == true ]]; then
    msg '#building with stubdom'
    source+=(
        http://xenbits.xen.org/xen-extfiles/lwip-1.3.0.tar.gz
        http://xenbits.xen.org/xen-extfiles/zlib-1.2.3.tar.gz
        http://xenbits.xen.org/xen-extfiles/newlib-1.16.0.tar.gz
        http://xenbits.xen.org/xen-extfiles/pciutils-2.2.9.tar.bz2
        http://xenbits.xen.org/xen-extfiles/polarssl-1.1.4-gpl.tgz
        http://xenbits.xen.org/xen-extfiles/grub-0.97.tar.gz
        http://xenbits.xen.org/xen-extfiles/tpm_emulator-0.7.4.tar.gz
        http://xenbits.xen.org/xen-extfiles/gmp-4.3.2.tar.bz2
        http://caml.inria.fr/pub/distrib/ocaml-3.11/ocaml-3.11.0.tar.gz
    )
fi


noextract=(
    "ipxe-git-$_git_tag_ipxe.tar.gz"
)

if [[ "$_build_stubdom" == true ]]; then
    noextract+=(
        lwip-1.3.0.tar.gz
        zlib-1.2.3.tar.gz
        newlib-1.16.0.tar.gz
        pciutils-2.2.9.tar.bz2
        polarssl-1.1.4-gpl.tgz
        grub-0.97.tar.gz
        tpm_emulator-0.7.4.tar.gz
        gmp-4.3.2.tar.bz2
        ocaml-3.11.0.tar.gz
    )
fi

validpgpkeys=('23E3222C145F4475FA8060A783FE14C957E82BD9')
#gpg --keyserver pgp.mit.edu --recv-key 23E3222C145F4475FA8060A783FE14C957E82BD9
sha256sums=('0262a7023f8b12bcacfb0b25e69b2a63291f944f7683d54d8f33d4b2ca556844'
            'SKIP'
            '251e5516d7de470c434ae5c393aacca2b61fb24d93770592a4a20add60b785c4'
            'SKIP'
            'SKIP'
            'd93c2d5bcdf0c3e4c6e8efb357cb4b9d618209025361f5ccd9d03651a8acd7a3'
            '5fb65130f96d1728368a09042e55f622c14117572030ce2141bff4ae150e4a01'
            '55145ff9c1570257478842e4001b0dafe007d90f5b06db17231bc5bf20f3b23d'
            '8101316cfdf4b59e9c39b7372d4240a4552971c0fa53a4719bbb7a22f5622f4e'
            'efb3c5713d556aa4890136ebf61502060cf90234fbd2e85701ad7a7ed2524fb1'
            '40e0760810a49f925f2ae9f986940b40eba477dc6d3e83a78baaae096513b3cf'
            'bba1abb5e4368421de29385e37f8477bf3534d3ba3ff7e2aae9c9d3da53f1393')


if [[ "$_build_stubdom" == true ]]; then
    sha256sums+=(
        #stubdom bits
        '772e4d550e07826665ed0528c071dd5404ef7dbe1825a38c8adbc2a00bca948f'
        '1795c7d067a43174113fdf03447532f373e1c6c57c08d61d9e4e9be5e244b05e'
        'db426394965c48c1d29023e1cc6d965ea6b9a9035d8a849be2750ca4659a3d07'
        'f60ae61cfbd5da1d849d0beaa21f593c38dac9359f0b3ddc612f447408265b24'
        '2d29fd04a0d0ba29dae6bd29fb418944c08d3916665dcca74afb297ef37584b6'
        '4e1d15d12dbd3e9208111d6b806ad5a9857ca8850c47877d36575b904559260b'
        '4e48ea0d83dd9441cc1af04ab18cd6c961b9fa54d5cbf2c2feee038988dea459'
        '936162c0312886c21581002b79932829aa048cfaf9937c6265aeaa14f1cd1775'
        'ecdd4f8473ab0dee5d3acb5c0a31a4c1dd6aa12179895cf1903dd0f455c43a4f'

        #stubdom patches
    )
fi

_xen_kconfig_debug=$(cat <<EOF
CONFIG_DEBUG=y
CONFIG_CRASH_DEBUG=y
EOF
)
_xen_kconfig_livepatch=$(cat <<EOF
CONFIG_LIVEPATCH=y
EOF
)

_makevars=(
    LANG=C
    PYTHON=python2
)

prepare() {
    cd "$_pkgname-$_pkgver/"

    ### Copy git sourced tools/firmware
    # move seabios into place
    mv --force "$srcdir/seabios" tools/firmware/seabios-dir-remote
    # move ovmf into place
    mv --force "$srcdir/ovmf" tools/firmware/ovmf-dir-remote

    ### Patching

    # XSA Patches
    msg 'XSA patches'
    # Security Patches - Base
    patch -Np1 -i "$srcdir/xsa253.patch"

    # Security Patches - qemu-xen-traditional
    cd 'tools/qemu-xen-traditional/'
    cd '../../'

    # Security Patches - qemu-xen (upstream)
    cd 'tools/qemu-xen/'
    cd '../../'


    # Compile Patches
    msg 'Compile patches'

    # Build EFI binary with mingw
    if [[ "$_binutils_efi" != true ]]; then
        if $(stat /usr/x86_64-w64-mingw32/bin/ld >/dev/null 2>&1); then
            sed -i.bak '/ EFI_LD/s/LD/LD_EFI/' xen/arch/x86/Makefile
            sed -i.bak 's/LD/LD_EFI/' xen/arch/x86/efi/Makefile
            sed -i.bak '/EFI_MOUNTPOINT .*/aLD_EFI ?= $(LD)' xen/Makefile
        else
            echo '#Not capable of building xen.efi. Need either:'
            echo '#(preferred) binutils compiled with --enable-targets=x86_64-pep'
            echo '#or install mingw-w64-binutils'
        fi
    fi

    # OVMF Compile support (Pulls from GIT repo, so patching to patch after pull request)
    patch -Np1 -i "$srcdir/patch-ovmf-use-python2.patch"
    #mkdir -p tools/firmware/ovmf-patches
    #cp "$srcdir"/patch-inbuild-ovmf*.patch tools/firmware/ovmf-patches/

    # Uncomment line below if you want to enable ATI Passthrough support (some reported successes, untested with 4.4)
    #patch -Np1 -i "$srcdir/ati-passthrough.patch"

    ## Fix fixed rundir paths
    ## grep -Rl '\/var\/run\/xen' * 2> /dev/null
    _var_run_fixed_paths=(
        tools/hotplug/Linux/locking.sh
        tools/xenmon/xenbaked.c
        tools/xenmon/xenmon.py
        tools/pygrub/src/pygrub
    )
    sed -i 's:/var/run:/run:' ${_var_run_fixed_paths[@]}

    ## Fix python version in shebang
    msg 'Fix python shebang to python2'
    _python_files=( $(grep -Rlse '^#!/usr/bin/.*python$' || : ) )
    sed -Ei 's|(^#!.*/usr/bin/(env ){0,1})python$|\1python2|' ${_python_files[@]}

    ## Fix systemd-modules-load.d/xen.conf
    ## remove nonexistent modules
    find tools -iname 'configure*' -exec sed -i -E -e '
        /^LINUX_BACKEND_MODULES="$/,/^"$/ {
            #Address range where this variable is set
            /"/b;               #Do noting if the line contains "
            /^xen-/!d;          #Delete if does not start with xen
            s/scsibk/scsiback/; #Change scsibk to scsiback
        };' {} \;

    if [[ "$_build_stubdom" == true ]]; then
        # Copy supporting tarballs into place
        ln -s "$srcdir/lwip-1.3.0.tar.gz" stubdom/
        ln -s "$srcdir/zlib-1.2.3.tar.gz" stubdom/
        ln -s "$srcdir/newlib-1.16.0.tar.gz" stubdom/
        ln -s "$srcdir/pciutils-2.2.9.tar.bz2" stubdom/
        ln -s "$srcdir/polarssl-1.1.4-gpl.tgz" stubdom/
        ln -s "$srcdir/grub-0.97.tar.gz" stubdom/
        ln -s "$srcdir/tpm_emulator-0.7.4.tar.gz" stubdom/
        ln -s "$srcdir/gmp-4.3.2.tar.bz2" stubdom/
        ln -s "$srcdir/ocaml-3.11.0.tar.gz" stubdom/

        ## Stubdom patches
        cd 'extras/mini-os'
        cd '../../'

        #vtpm
    fi

    #etherboot
    ln -s "$srcdir/ipxe-git-$_git_tag_ipxe.tar.gz" tools/firmware/etherboot/ipxe.tar.gz
    #cp "$srcdir"/patch-inbuild-ipxe*.patch tools/firmware/etherboot/patches/
}

build() {
    cd "$_pkgname-$_pkgver/"
    export LD_EFI='/usr/x86_64-w64-mingw32/bin/ld'
    ./autogen.sh
    if [[ "$_build_stubdom" == true ]]; then
        _config_stubdom=(--enable-stubdom)
        _config_stubdom+=(
            #--enable-ioemu-stubdom=no
            #--enable-c-stubdom=no
            #--enable-caml-stubdom=no
            #--enable-pv-grub=no
            #--enable-xenstore-stubdom=no
            #--enable-vtpm-stubdom=no
            #--enable-vtpmmgr-stubdom=no
        )
    else
        _config_stubdom=(--disable-stubdom)
    fi
    _config_seabios=()
    if [[ "$_system_seabios" == true ]]; then
        _config_seabios=(--with-system-seabios=/usr/share/qemu/bios-256k.bin)
    fi
    _config_xen_kconfig=''
    _config_debug=()
    if [[ "$_build_debug" == true ]]; then
        _config_debug=(--enable-debug --enable-debug-tcg --enable-debug-info)
        _config_xen_kconfig+="\n$_xen_kconfig_debug"
        _makevars+=(debug=y CONFIG_DEBUG=y)
    fi
    if [[ "$_build_livepatch" == true ]]; then
        _config_xen_kconfig+="\n$_xen_kconfig_livepatch"
    fi
    if [[ -n "$_config_xen_kconfig" ]]; then
        cd xen
        echo -e "$_config_xen_kconfig" > .config
        make "${_makevars[@]}" olddefconfig V=1
        cd ../
    fi
    ./configure PYTHON=/usr/bin/python2 --prefix=/usr --sbindir=/usr/bin --with-sysconfig-leaf-dir=conf.d --with-rundir=/run \
        --enable-systemd --enable-ovmf \
        "${_config_seabios[@]}" \
        "${_config_stubdom[@]}" \
        "${_config_debug[@]}" \
        --with-extra-qemuu-configure-args='--disable-bluez --disable-gtk --enable-spice --enable-usb-redir'
        #--with-system-qemu --with-system-seabios --with-system-ovmf 
        #defaults --enable-qemu-traditional --enable-rombios \
    make "${_makevars[@]}" dist
    if [[ "$_build_livepatch" == true ]]; then
        make "${_makevars[@]}" build-tests
    fi
}

package_xen() {
    _makevars_package=("${_makevars[@]}" DESTDIR="$pkgdir")
    optdepends=(
        'xen-docs: Official Xen documentation'
        'openvswitch: Optional advanced networking support'
        'urlgrabber: Required for xenpvnetboot'
    )
    conflicts=(xen-{git,rc,igvtg,4.{8,9}} xenstore)
    provides=(xenstore)
    replaces=(xen-{git,rc,4.{8,9}})
    backup=(
        etc/conf.d/xen{domains,commons}
        "etc/$_pkgname/grub.conf"
        "etc/$_pkgname/oxenstored.conf"
        "etc/$_pkgname/xl.conf"
    )
    install="$_pkgname.install"

    cd "$_pkgname-$_pkgver/"

    make "${_makevars_package[@]}" install-xen
    make "${_makevars_package[@]}" install-tools
    if [[ "$_build_stubdom" == true ]]; then
        make "${_makevars_package[@]}" install-stubdom
    fi
    if [[ "$_build_livepatch" == true ]]; then
        make "${_makevars_package[@]}" install-tests
    fi

    cd "$pkgdir"

    # Install files from Parabola package
    install -Dm644 "$srcdir/tmpfiles.d-$_pkgname.conf" "usr/lib/tmpfiles.d/$_pkgname.conf"
    install -Dm755 "$srcdir/21_linux_xen_multiboot_arch" etc/grub.d/21_linux_xen_multiboot_arch
    install -Dm644 "$srcdir/efi-xen.cfg" etc/xen/efi-xen.cfg

    mkdir -p var/log/xen/console

    # Sanitize library path (if lib64 exists)
    if [[ -d usr/lib64 ]]; then
        cd usr/
        mv lib64/* lib/
        rmdir lib64
        cd ../
    fi

    # If EFI binaries built, move to /boot
    if [[ -f usr/lib/efi/xen.efi ]]; then
        mv usr/lib/efi/*.efi boot/
        rmdir usr/lib/efi
    fi

    # Remove syms
    find usr/lib/debug -type f \( -name '*-syms*' -or -name '*\.map' \) -delete
    rmdir --ignore-fail-on-non-empty usr/lib/debug

    # Remove hypervisor boot symlinks
    rm -f boot/xen{,-4{,.8,.9}}{,.{gz,efi}}

    # Documentation cleanup ( see xen-docs package )
    #rm -rf usr/share/doc
    #rm -rf usr/share/man

    # Remove tempdirs
    rmdir run/xen{,stored}
    rmdir run

    # Remove unnecessary qemu ELF support files
    # qemuu
    rm -f usr/share/qemu-xen/qemu/{palcode,openbios,s390}-*
    rm -f usr/share/qemu-xen/qemu/u-boot.e500
    # qemut 
    if [[ "$CARCH" == *'x86'* ]]; then
        rm -f usr/share/xen/qemu/openbios-*
    fi

    # adhere to Static Library Packaging Guidelines
    rm -rf usr/lib/*.a

    # Remove unneeded init.d files
    rm -rf etc/init.d
}

package_xen-docs(){
    _makevars_package=("${_makevars[@]}" DESTDIR="$pkgdir")
    pkgdesc='Xen virtual machine hypervisor documentation'
    arch=('any')
    depends=()
    cd "$_pkgname-$_pkgver/"
    make "${_makevars_package[@]}" install-docs
}

package_xen-syms(){
    _makevars_package=("${_makevars[@]}" DESTDIR="$pkgdir")
    pkgdesc='Xen virtual machine hypervisor debugging symbols'
    arch=('any')
    depends=()
    _installdir="${pkgdir}/usr/lib/debug"
    cd "$_pkgname-$_pkgver/"
    install -d -m0755 "$_installdir"
    for _path in $(find xen -type f \( -name '*-syms' -or -name '*\.map' \)); do
        _file=$(basename "$_path")
        _installfile=$(echo "$_file" |
                       sed "s/\([^.]*\)\(\.*\)/\1-${_pkgver}\2/" )
        install -D -m0644 -p "$_path" "$_installdir/$_installfile"
    done
}
