#!/bin/env bash
#====================================================================
# Description: OpenResty Installation Script / OpenResty 安装脚本
# Author: Liu YanHao
# Create Time: 2024-11-15
# Last Modified: 2025-06-13
# Modified by: Zhang JinWei
# Version: 1.2
# Usage: ./install_openresty.sh
# Example: ./install_openresty.sh
#====================================================================
set -e

# ----------------------------------------Define constants / 定义常量----------------------------------------
readonly OPENRESTY_DIR="/usr/local/openresty"
readonly CACHE_DIR="/data/cache"
readonly INSTALL_PKG_DIR="/root/cdninstall/pkg/openresty"
readonly GEOIP_DIR="/usr/share/GeoIP"

# ----------------------------------------Install dependencies / 安装依赖----------------------------------------
function install_dependencies() {
    apt-get update
    apt-get install -y wget build-essential libpcre3 libpcre3-dev libssl-dev \
        zlib1g zlib1g-dev libgd3 libgd-dev libmaxminddb0 libbrotli-dev \
        libmaxminddb-dev

    ln -sf /usr/lib/x86_64-linux-gnu/libpcre.so.3 /usr/lib/x86_64-linux-gnu/libpcre.so.1
    ln -sf /usr/lib/x86_64-linux-gnu/libgd.so.3 /usr/lib/x86_64-linux-gnu/libgd.so.2

}

# ----------------------------------------Setup GeoIP database / 配置GeoIP数据库----------------------------------------
function setup_geoip() {
    rm -rf "${GEOIP_DIR}" && mkdir -p "${GEOIP_DIR}"
    curl -Lo ${GEOIP_DIR}/GeoLite2-Country.mmdb "http://deb.aorta.global/SuperCDN/Geo/GeoLite2-Country_latest/GeoLite2-Country.mmdb" ||
        wget -O ${GEOIP_DIR}/GeoLite2-Country.mmdb "http://deb.aorta.global/SuperCDN/Geo/GeoLite2-Country_latest/GeoLite2-Country.mmdb"
    curl -Lo ${GEOIP_DIR}/GeoLite2-ASN.mmdb "http://deb.aorta.global/SuperCDN/Geo/GeoLite2-ASN_latest/GeoLite2-ASN.mmdb" ||
        wget -O ${GEOIP_DIR}/GeoLite2-ASN.mmdb "http://deb.aorta.global/SuperCDN/Geo/GeoLite2-ASN_latest/GeoLite2-ASN.mmdb"
}

# ----------------------------------------Install OpenResty / 安装OpenResty----------------------------------------
function install_openresty() {
    if [[ -d "${OPENRESTY_DIR}" ]]; then
        systemctl stop nginx
        systemctl disable nginx
        rm -rf /usr/local/openresty.tgz "${OPENRESTY_DIR}"
    fi
    \cp "${INSTALL_PKG_DIR}"/cdn-openresty-main-*.tgz /usr/local/openresty.tgz && tar -xzf /usr/local/openresty.tgz -C /usr/local/
}

# ----------------------------------------Setup systemd service / 配置系统服务----------------------------------------
function setup_service() {
cat >/usr/lib/systemd/system/nginx.service <<'EOF'
[Unit]
Description=The OpenResty HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target
Wants=network-online.target
Documentation=https://openresty.org/

[Service]
Type=forking
PIDFile=/usr/local/openresty/nginx/logs/nginx.pid
ExecStartPre=/usr/local/openresty/nginx/sbin/nginx -t -c /usr/local/openresty/nginx/conf/nginx.conf
ExecStart=/usr/local/openresty/nginx/sbin/nginx -c /usr/local/openresty/nginx/conf/nginx.conf
ExecReload=/usr/local/openresty/nginx/sbin/nginx -s reload
ExecStop=/usr/local/openresty/nginx/sbin/nginx -s quit

LimitNOFILE=1048576
LimitNPROC=1048576
LimitCORE=infinity
LimitMEMLOCK=infinity

Restart=on-failure
RestartSec=5s
WorkingDirectory=/usr/local/openresty/nginx
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
    chmod +x /usr/lib/systemd/system/nginx.service
}

# ----------------------------------------Configure environment / 配置环境----------------------------------------
function configure_environment() {
    echo "export CDN_DOMAIN_CONF=${OPENRESTY_DIR}/nginx" >/etc/profile.d/CDN_DOMAIN_CONF.sh
    source /etc/profile.d/CDN_DOMAIN_CONF.sh
    ln -sf "${OPENRESTY_DIR}/nginx/sbin/nginx" /usr/bin/nginx
}

# ----------------------------------------Main function / 主函数----------------------------------------
function main() {
    # Create cache directory / 创建缓存目录
    mkdir -p "${CACHE_DIR}"

    # Stop existing service if running / 如果服务正在运行则停止
    if [[ -d "${OPENRESTY_DIR}" ]]; then
        systemctl stop nginx
        systemctl disable nginx
    fi

    install_dependencies
    setup_geoip
    install_openresty

    # Verify configuration / 验证配置
    if ! "${OPENRESTY_DIR}/nginx/sbin/nginx" -t; then
        echo -e "\e[31mNginx configuration test failed / Nginx配置测试失败\e[0m"
        echo "检查依赖问题:"
        ldd "${OPENRESTY_DIR}/nginx/sbin/nginx"
        exit 1
    fi

    setup_service
    configure_environment

    # Reload and start service / 重载并启动服务
    systemctl daemon-reload
    systemctl enable --now nginx.service
}

main
