echo "3CX WebAPI nginx config update process"

NGINX_PATH1="/etc/nginx/sites-enabled/3cxpbx"
NGINX_PATH2="/var/lib/3cxpbx/Bin/nginx/conf/nginx.conf"
echo "nginx config setting"
NGINX_CONFIG_LINE="location ~ ^/webapi/?(.*) \n{\n\nproxy_set_header Upgrade \"\"$\"\"http_upgrade;\nproxy_set_header Connection \"\"$\"\"connection_upgrade;\nproxy_set_header Host \"\"$\"\"host;\nproxy_set_header X-Forwarded-Proto \"\"$\"\"scheme;\nproxy_set_header X-Forwarded-For \"\"$\"\"proxy_add_x_forwarded_for;\nproxy_pass http://127.0.0.1:8081/webapi/\"\"$\"\"1\"\"$\"\"is_args\"\"$\"\"args;\nproxy_buffering off;\n}"

echo "Checking nginx configuration"

FILE_RESULT=$(grep -o "webapi" $NGINX_PATH2)

if [[ -n "$FILE_RESULT" ]]; then
    echo "nginx config is already set. Performing exit"
    exit 1
else
    echo "nginx config is ready for update"
fi

configLine_Path1=$(grep -n --line-number "location /manager {" $NGINX_PATH1 | cut -f1 -d:)i
configLine_Path2=$(grep -n --line-number "location /manager {" $NGINX_PATH2 | cut -f1 -d:)i

sedString1="$configLine_Path1 $NGINX_CONFIG_LINE"
sedString2="$configLine_Path2 $NGINX_CONFIG_LINE"

#echo $sedString1

eval "sed -i \"$sedString1\" $NGINX_PATH1"
eval "sed -i \"$sedString2\" $NGINX_PATH2"

echo "nginx config finished. Restarting nginx service"
systemctl restart nginx

sleep 3s

#systemctl start webapi
echo "nginx restarted"
echo "Setting up Lame for mp3 support"

echo "Testing WebAPI startup"
/var/www/webapi/TCXWebAPI --urls=http://127.0.0.1:8081 &
sleep 10
kill $!
echo "WebAPI startup test finished. Starting WebAPI service"
systemctl start webapi
exit 0