#!/bin/sh /etc/rc.common
# Copyright (C) 2018-2022 Lienol <lawlienol@gmail.com>

START=99

CONFIG="kodexplorer"

TEMP_PATH="/var/etc/$CONFIG"
NGINX_CONFIG="$TEMP_PATH/nginx.conf"
PHP_CONFIG="$TEMP_PATH/php.ini"
PHP_FPM_CONFIG="$TEMP_PATH/php-fpm.conf"
PHP_FPM_SOCK="$TEMP_PATH/php-fpm.sock"

config_t_get() {
	local index=0
	[ -n "$4" ] && index=$4
	local ret=$(uci get $CONFIG.@$1[$index].$2 2>/dev/null)
	echo ${ret:=$3}
}

gen_nginx_config() {
	ipv6=$(config_t_get global ipv6 0)
	port=$(config_t_get global port)
	[ "$(config_t_get global https 0)" == "1" ] && {
		port="$port ssl"
		ssl_certificate="ssl_certificate $(config_t_get global certificate);"
		ssl_certificate_key="ssl_certificate_key $(config_t_get global key);"
	}
	sed -e "s#|PID|#$TEMP_PATH/nginx.pid#g" \
	    -e "s#|PORT|#$port#g" \
	    -e "s#|ssl_certificate|#$ssl_certificate#g" \
	    -e "s#|ssl_certificate_key|#$ssl_certificate_key#g" \
	    -e "s#|project_directory|#$project_directory#g" \
	    -e "s#|SOCK|#$PHP_FPM_SOCK#g" \
	    -e "s#|upload_max_filesize|#$upload_max_filesize#g" \
	    -e "s#|temp_path|#$TEMP_PATH/temp#g" \
	    /etc/$CONFIG/nginx.conf.template > $1
		
	[ "$ipv6" = "0" ] && sed -i '/listen \[::\]:/d' $1
}

gen_php_config() {
	sed -e "s#|project_directory|#$project_directory#g" \
	    -e "s#|open_basedir|#$open_basedir#g" \
	    -e "s#|memory_limit|#$memory_limit#g" \
	    -e "s#|upload_max_filesize|#$upload_max_filesize#g" \
	    /etc/$CONFIG/php.ini.template > $PHP_CONFIG
	
	sed -e "s#|PID|#$TEMP_PATH/php-fpm.pid#g" \
	    -e "s#|ERROR_LOG|#$TEMP_PATH/php-fpm.log#g" \
	    -e "s#|SOCK|#$PHP_FPM_SOCK#g" \
	    /etc/$CONFIG/php-fpm.conf.template > $PHP_FPM_CONFIG
}

start() {
	ENABLED=$(config_t_get global enable 0)
	[ "$ENABLED" = "0" ] && return 0
	mkdir -p $TEMP_PATH $TEMP_PATH/temp /var/log/nginx /var/lib/nginx
	memory_limit=$(config_t_get global memory_limit 64M)
	upload_max_filesize=$(config_t_get global upload_max_filesize 64M)
	project_directory=$(config_t_get global project_directory)
	open_basedir=$(config_t_get global open_basedir "/")
	open_basedir=$(echo $open_basedir | sed "s/ /:/g")
	gen_php_config
	/usr/bin/php8-fpm -c $PHP_CONFIG -R -y $PHP_FPM_CONFIG
	gen_nginx_config $NGINX_CONFIG
	/usr/sbin/nginx -c $NGINX_CONFIG >/dev/null 2>&1 &
}

stop() {
	/usr/sbin/nginx -c $NGINX_CONFIG -s stop >/dev/null 2>&1
	[ -f "$TEMP_PATH/php-fpm.pid" ] && kill -2 $(cat $TEMP_PATH/php-fpm.pid) >/dev/null 2>&1
	rm -rf $TEMP_PATH
}

restart() {
	stop
	start
}