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

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

# ----------------------------------------Install dependencies / 安装依赖----------------------------------------
function install_dependencies() {
    yum install -y wget gcc gcc-c++ pcre pcre-devel openssl openssl-devel \
        zlib zlib-devel gd gd-devel epel-release libmaxminddb brotli-devel \
        libmaxminddb-devel
}

# ----------------------------------------Setup GeoIP database / 配置GeoIP数据库----------------------------------------
function setup_geoip() {
    rm -rf "${GEOIP_DIR}" && mkdir -p "${GEOIP_DIR}"
    curl -o "${GEOIP_DIR}/GeoLite2-Country_latest.tar.gz" "http://deb.aorta.global/SuperCDN/Geo/GeoLite2-Country_latest.tar.gz" && tar -xzf "${GEOIP_DIR}/GeoLite2-Country_latest.tar.gz" -C "${GEOIP_DIR}"
    \cp "${GEOIP_DIR}"/GeoLite2-Country_20*/GeoLite2-Country.mmdb "${GEOIP_DIR}"
}

# ----------------------------------------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}/openresty.tgz" /usr/local/ && tar -xzf /usr/local/openresty.tgz -C /usr/local/
}

# ----------------------------------------Configure Nginx / 配置Nginx----------------------------------------
function configure_nginx() {
    local conf_files=(
        "nginx.conf"
        "gzip.conf"
        "brotli.conf"
        "zstd.conf"
        "cache.conf"
        "server.conf"
    )

    # Copy configuration files / 复制配置文件
    for conf in "${conf_files[@]}"; do
        \cp -f "${INSTALL_PKG_DIR}/nginx_conf/${conf}" "${NGINX_CONF_DIR}/${conf}"
    done

    # Copy SSL certificates / 复制SSL证书
    \cp -f "${INSTALL_PKG_DIR}/server.crt" "${OPENRESTY_DIR}/nginx/certs/"
    \cp -f "${INSTALL_PKG_DIR}/server.key" "${OPENRESTY_DIR}/nginx/certs/"

    # Configure default server / 配置默认服务器
    \cp -f "${INSTALL_PKG_DIR}/nginx_conf/default.conf" "${OPENRESTY_DIR}/nginx/conf.d/default.conf"
    \cp -f "${INSTALL_PKG_DIR}/nginx_conf/traffic_status.conf" "${OPENRESTY_DIR}/nginx/conf.d/traffic_status.conf"

    # Copy lua scripts / 复制lua脚本
    \cp -f "${INSTALL_PKG_DIR}/lualib/body_filter.lua" "${OPENRESTY_DIR}/nginx/lualib/body_filter.lua"
    \cp -f "${INSTALL_PKG_DIR}/lualib/hls.lua" "${OPENRESTY_DIR}/nginx/lualib/hls.lua"
}

# ----------------------------------------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

[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=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
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
    configure_nginx

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

    setup_service
    configure_environment

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

main
