#!/bin/bash

# Copyright: 2023 Virtuozzo International GmbH

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.



[ -n "${NGINXPHPDEPLOYLIB_VERSION:-}" ] && return 0;
NGINXPHPDEPLOYLIB_VERSION="0.1";
DEFAULT_CONTEXT="ROOT";
NGINX_ALIASES_FILE="/etc/nginx/aliases.conf";
include os;

function setContext(){
  local context=$1;
  WEBROOT1=$( $SED "s/\//\\\\\\//g" <<< ${WEBROOT} );
  if [[ "$context" != "$DEFAULT_CONTEXT" ]]; then
    $SED -i "/^location\s\{0,\}\/${context}\s\{0,\}{\s\{0,\}alias\s\{0,\}${WEBROOT1}\/${context};\s\{0,\}}/d"  $NGINX_ALIASES_FILE;
    echo "location /${context} { alias ${WEBROOT}/${context}; }" >> $NGINX_ALIASES_FILE;
  fi
  reloadServiceSilent nginx || { stopServiceSilent nginx; startServiceSilent nginx; }
}

function delContext(){
  local context=$1;
    
   # Alias /error/ "/var/www/error/"

   WEBROOT1=$( $SED "s/\//\\\\\\//g" <<< ${WEBROOT} );
   if [[ "$context" != "$DEFAULT_CONTEXT" ]]; then
     $SED -i "/^location\s\{0,\}\/${context}\s\{0,\}{\s\{0,\}alias\s\{0,\}${WEBROOT1}\/${context};\s\{0,\}}/d"  $NGINX_ALIASES_FILE;
   fi
   reloadServiceSilent nginx || { stopServiceSilent nginx; startServiceSilent nginx; }
}


function rename(){
    local newContext=$1;
    local oldContext=$2;
    WEBROOT1=$( $SED "s/\//\\\\\\//g" <<< ${WEBROOT} );
    if [[ "$oldContext" != "$DEFAULT_CONTEXT" ]]; then
      $SED -i "s/^location\s\{0,\}\/${oldContext}\s\{0,\}{\s\{0,\}alias\s\{0,\}${WEBROOT1}\/${oldContext};\s\{0,\}}/location \/${newContext} { alias ${WEBROOT1}\/${newContext}; }/"  $NGINX_ALIASES_FILE;
    fi
    reloadServiceSilent nginx || { stopServiceSilent nginx; startServiceSilent nginx; }
}
