# Copyright (c) 2024 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: chenyajie <chenyajie5@huawei-partners.com>
# Maintainer: huangminzhong <huangminzhong2@huawei.com>

pkgname=postgresql
pkgver=16.3
pkgrel=0
pkgdesc="PostgreSQL is a powerful open-source object-relational database system."
url="https://www.postgresql.org/"
archs=("armeabi-v7a" "arm64-v8a")
license=("PostgreSQL License")
depends=("icu" "tzdb")
makedepends=()

source="https://ftp.postgresql.org/pub/source/v${pkgver}/${pkgname}-${pkgver}.tar.gz"

downloadpackage=true

builddir=$pkgname-${pkgver}
packagename=$builddir.tar.gz
buildtools="configure"
patch_flag=true
ln_flag=true
source envset.sh
host=

prepare() {
    if [ "$patch_flag" == true  ]
    then
        cd $builddir
        patch -p1 < ../postgresql_ohos_pkg.patch > $buildlog 2>&1  
        cd $OLDPWD
        patch_flag=false
    fi
    cp -arf $builddir $builddir-$ARCH-build
    if [ $ARCH == "armeabi-v7a" ]
    then
        setarm32ENV
        host=arm-linux
    elif [ $ARCH == "arm64-v8a" ]
    then
        setarm64ENV
        host=aarch64-linux
    else
        echo "${ARCH} not support"
        return -1
    fi
}

build() {
    cd $builddir-$ARCH-build
    export LDFLAGS_EX_BE="-Wl,--export-dynamic" #源库交叉编译默认关闭server服务,需手动开启
    export ICU_CFLAGS="-I${LYCIUM_ROOT}/usr/icu/${ARCH}/include"
    export ICU_LIBS="-L${LYCIUM_ROOT}/usr/icu/${ARCH}/lib -licuuc -licui18n -licudata"
    ./configure --without-readline --enable-debug "$@" --host=$host > $buildlog 2>&1

    sed -i 's/\/usr\/bin\/install/\/bin\/install/g' ./src/Makefile.global
    sed -i 's/\/usr\/bin\/mkdir/\/data\/CIusr\/bin\/mkdir/g' ./src/Makefile.global
    sed -i 's/\/usr\/sbin\/zic/\/data\/bin\/zic/g' ./src/Makefile.global

    $MAKE > $buildlog 2>&1
    ret=$?
    cd $OLDPWD
    return $ret
}

package() {
    if [ "$ln_flag" == true ]
    then
        mkdir -p /data/CIusr/bin
        mkdir -p /data/bin
        ln -s /usr/sbin/zic /data/bin
        ln -s /bin/mkdir /data/CIusr/bin
        ln_flag=false
    fi
    cd $builddir-$ARCH-build
    $MAKE install >> $buildlog 2>&1
    cd $OLDPWD
}

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


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