#!/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 "${APACHEPHPDEPLOYLIB_VERSION:-}" ] && return 0;
APACHEPHPDEPLOYLIB_VERSION="0.1";

HTTPD_ALIASES_FILE="/etc/httpd/conf.d/aliases.conf";
DEFAULT_CONTEXT="ROOT";
include os;
$PROGRAM 'sed';

function setContext(){
    local context=$1;
    
   # Alias /error/ "/var/www/error/"
   $SED -i "/Alias\s\{1,\}\/${context}\s\{1,\}.*/d" $HTTPD_ALIASES_FILE;
   if [[ "$context" != "$DEFAULT_CONTEXT" ]]; then
     echo "Alias /${context} \"${WEBROOT}/${context}\"" >> $HTTPD_ALIASES_FILE;
   fi
   reloadService ${SERVICE} > /dev/null 2>&1;
}

function delContext(){
    local context=$1;
    
   # Alias /error/ "/var/www/error/"
   
   WEBROOT1=$( $SED "s/\//\\\\\\//g" <<< ${WEBROOT} );
   if [[ "$context" != "$DEFAULT_CONTEXT" ]]; then
     $SED -i "/^Alias\s\{0,\}\/${context}\s\{0,\}\"${WEBROOT1}\/${context}\"/d"  $HTTPD_ALIASES_FILE;
   fi
   reloadService ${SERVICE} > /dev/null 2>&1;
}


function rename(){
    local newContext=$1;
    local oldContext=$2;
    WEBROOT1=$( $SED "s/\//\\\\\\//g" <<< ${WEBROOT} );
    if [[ "$oldContext" != "$DEFAULT_CONTEXT" ]]; then
      $SED -i "s/^Alias\s\{0,\}\/${oldContext}\s\{0,\}\"${WEBROOT1}\/${oldContext}\"/Alias \/${newContext} \"${WEBROOT1}\/${newContext}\"/" $HTTPD_ALIASES_FILE;
    fi
    reloadService ${SERVICE} > /dev/null 2>&1;
}
