# Copyright (c) 2023 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License

# Contributor: Jeff Han <hanjinfei@foxmail.com>, wupingyuan <3415239542@qq.com>
# Maintainer: Jeff Han <hanjinfei@foxmail.com>
pkgname=openh264
pkgver=v2.4.1
pkgrel=0
pkgdesc="Open Source H.264 Codec"
url="http://www.openh264.org/"
archs=("armeabi-v7a" "arm64-v8a" "x86_64")
license=("BSD-2-Clause")
depends=()
makedepends=()

source="https://gitee.com/mirrors/$pkgname/repository/archive/$pkgver.tar.gz"

autounpack=true
downloadpackage=true
patchflag=true
buildtools="make"

builddir=$pkgname-${pkgver}
packagename=$builddir.tar.gz

source envset.sh

arch=
destdir=
prepare() {
    if $patchflag
    then
        cd $builddir
        # 由于x86_64编译报错ld.lld: error: undefined symbol: __fprintf_chk 
        # >>> referenced by welsCodecTrace.cpp 
        # >>> welsCodecTrace.o:(welsStderrTrace(void*, int, char const*)) in archive ./libcommon.a
        patch -p1 < `pwd`/../openh264_oh_pkg.patch
        patchflag=false
        cd $OLDPWD
    fi
    cp -rf $builddir $builddir-$ARCH-build
    # 创建安装目录
    mkdir -p $LYCIUM_ROOT/usr/$pkgname/$ARCH
    destdir=$LYCIUM_ROOT/usr/$pkgname/$ARCH/
    if [ $ARCH == "armeabi-v7a" ]
    then
        setarm32ENV
        arch=armeabi
    elif [ $ARCH == "arm64-v8a" ]
    then
        setarm64ENV
        arch=aarch64
    elif [ $ARCH == "x86_64" ]
    then
        setx86_64ENV
        arch=x86_64
    else
        echo "${ARCH} not support"
        return -1
    fi

    export CFLAGS=" -O3 -flto ${CFLAGS}"
    export CXXFLAGS=" -O3 -flto ${CXXFLAGS}"

}

#参数1
build() {
    cd $builddir-$ARCH-build
    envarch=$ARCH
    $MAKE PREFIX=$destdir ARCH=$arch OS=linux > $buildlog 2>&1
    ret=$?
    cd $OLDPWD
    ARCH=$envarch
    return $ret
}

package() {
    cd $builddir-$ARCH-build
    envarch=$ARCH
    $MAKE install-static ARCH=$arch PREFIX=$destdir >> $buildlog 2>&1
    ARCH=$envarch
    cd $OLDPWD
}

check() {
    unset arch
    unset destdir
    if [ $ARCH == "armeabi-v7a" ]
    then
        unsetarm32ENV
    elif [ $ARCH == "arm64-v8a" ]
    then
        unsetarm64ENV
    elif [ $ARCH == "x86_64" ]
    then
        unsetx86_64ENV
    else
        echo "${ARCH} not support"
        return -1
    fi
    echo "The test must be on an OpenHarmony device!"
}

# 清理环境
cleanbuild() {
    rm -rf ${PWD}/$builddir $builddir-armeabi-v7a-build $builddir-arm64-v8a-build $builddir-x86_64-build #${PWD}/$packagename
}
