#!/bin/bash

set -e

# 设置工作路径为当前脚本所在目录
BASE_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$BASE_DIR"

echo ">>> 当前工作目录: $BASE_DIR"

PG_DIR="/usr/local/pgsql"

# 检查是否已编译安装 oracle_fdw
echo "检查是否已编译安装 oracle_fdw..."
PG_LIB_DIR="$PG_DIR/lib"
PG_SHARE_DIR="$PG_DIR/share/extension"

# 搜索 oracle_fdw.so 和 oracle_fdw.control
ORACLE_FDW_SO="$PG_LIB_DIR/oracle_fdw.so"
ORACLE_FDW_CONTROL="$PG_SHARE_DIR/oracle_fdw.control"

if [ -f "$ORACLE_FDW_SO" ] && [ -f "$ORACLE_FDW_CONTROL" ]; then
    echo "oracle_fdw 已编译安装（找到 ORACLE_FDW_SO 和 ORACLE_FDW_CONTROL），跳过安装步骤。"
    echo "ORACLE_FDW_SO: $ORACLE_FDW_SO"
    echo "ORACLE_FDW_CONTROL: $ORACLE_FDW_CONTROL"
    exit 0
else
    echo "未找到完整的 oracle_fdw 安装，继续安装过程..."
    echo "查找结果:"
    echo "  $ORACLE_FDW_SO: $( [ -f "$ORACLE_FDW_SO" ] && echo "存在" || echo "不存在" )"
    echo "  $ORACLE_FDW_CONTROL: $( [ -f "$ORACLE_FDW_CONTROL" ] && echo "存在" || echo "不存在" )"
fi

echo ">>> 解压 Oracle Instant Client 到 /opt/oracle..."
mkdir -p /opt/oracle
cp instantclient-*.zip /opt/oracle/
cd /opt/oracle

unzip -q instantclient-basic-linux.x64-21.13.0.0.0dbru.zip
unzip -q instantclient-sdk-linux.x64-21.13.0.0.0dbru.zip

cd instantclient_21_13
ln -sf libclntsh.so.21.1 libclntsh.so
ln -sf libocci.so.21.1 libocci.so

echo ">>> 配置环境变量..."
cat > /etc/profile.d/oracle.sh <<EOF
export ORACLE_HOME=/opt/oracle/instantclient_21_13
export LD_LIBRARY_PATH=\$ORACLE_HOME
export PATH=\$ORACLE_HOME:\$PATH
EOF

source /etc/profile.d/oracle.sh

echo ">>> 解压 oracle_fdw 源码..."
cd "$BASE_DIR"
rm -rf oracle_fdw-ORACLE_FDW_2_3_0
unzip -q oracle_fdw-ORACLE_FDW_2_3_0.zip

echo ">>> 编译 oracle_fdw..."
cd oracle_fdw-ORACLE_FDW_2_3_0

make PG_CONFIG="$PG_DIR/bin/pg_config"
make PG_CONFIG="$PG_DIR/bin/pg_config" install
# 为 PostgreSQL 设置系统级动态库路径
echo "/opt/oracle/instantclient_21_13" > /etc/ld.so.conf.d/oracle-instantclient.conf
ldconfig
# systemctl restart postgresql-13

echo ">>> oracle_fdw 安装完成！"
