# Copyright (c) 2025 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: dingchenjie1 <dingchenjie1@h-partners.com>
# Maintainer: dingchenjie1 <dingchenjie1@h-partners.com>

pkgname=leveldb
pkgver=1.23
pkgrel=0
pkgdesc="LevelDB is a fast key-value storage library written at Google that provides an ordered mapping from string keys to string values."
archs=("armeabi-v7a" "arm64-v8a")
license=("BSD-3-Clause")
makedepends=()
downloadpackage=false
autounpack=false
builddir=$pkgname-${pkgver}
cloneflag=true
buildtools="cmake"
patchflag=true

# 原库地址:https://github.com/google/leveldb.git
source="https://gitee.com/mirrors/${pkgname}.git"

# 1.23版本对应的commitid
commitid=99b3c03b3284f5886f9ef9a4ef703d57373e61be

prepare() {
    if $cloneflag
    then
        git clone --recurse-submodules $source $builddir > $publicbuildlog 2>&1
        if [ $? -ne 0 ]
        then
            return -1
        fi
        cd $builddir
        git reset --hard $commitid >> $publicbuildlog 2>&1
        if [ $? -ne 0 ]
        then
            cd $OLDPWD
            return -2
        fi
        cd $OLDPWD
        cloneflag=false
    fi

    if $patchflag
    then
        cd $builddir/util
        # 原库的一个测试用例获取当前进程所有文件描述符时会少获取一个fd,导致最后结果不正确,这里将获取逻辑执行两次,
        # 确保当前进程的所有fd正确获取。
        patch < ${PKGBUILD_ROOT}/leveldb_oh_test.patch
        patchflag=false
        cd $OLDPWD
    fi

    mkdir -p $builddir/$ARCH-build
}

build() {
    cd $builddir
    ${OHOS_SDK}/native/build-tools/cmake/bin/cmake "$@" -DCMAKE_C_FLAGS="-Wno-unused-command-line-argument" \
        -DCMAKE_CXX_FLAGS="-Wno-unused-command-line-argument" -B$ARCH-build -S./ > $buildlog 2>&1
    $MAKE VERBOSE=1 -C $ARCH-build >> $buildlog 2>&1
    ret=$?
    cd $OLDPWD
    return $ret
}

package() {
    cd $builddir
    $MAKE -C $ARCH-build install >> $buildlog 2>&1
    ret=$?
    cd $OLDPWD
    return $ret
}

check() {
    echo "The test must be on an OpenHarmony device!"
}

cleanbuild() {
    rm -rf ${PWD}/$builddir
    return $ret
}