#!/bin/bash
# info: updates web templates
# options: [RESTART]
#
# The function for obtaining updated pack of web templates.


#----------------------------------------------------------#
#                    Variable&Function                     #
#----------------------------------------------------------#

# Argument defenition
restart=$1

# Includes
source $VESTA/func/main.sh
source $VESTA/conf/vesta.conf


#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

# Find out OS name
if [ -e "/etc/redhat-release" ]; then
    os="rhel"
else
    os="ubuntu"
fi

# Get new archive
tmpdir=$(mktemp -d --dry-run)
mkdir $tmpdir
cd $tmpdir
wget http://c.vestacp.com/$VERSION/$os/templates.tar.gz -q
if [ "$?" -ne 0 ]; then
    echo "Error: can't download template.tar.gz"
    log_event "$E_CONNECT" "$EVENT"
    rm -rf $tmpdir
    exit $E_CONNECT
fi

# Update templates
tar -xzpf templates.tar.gz -C $VESTA/data/ templates/web

# Replace includes for apache2.4
if [ "$WEB_SYSTEM" = 'httpd' ] || [ "$WEB_SYSTEM" = 'apache2' ]; then
    if [ ! -z "$(/usr/sbin/apachectl -v | grep 'Apache/2.4')" ]; then
        sed -i "s/Include /IncludeOptional /g" \
            $VESTA/data/templates/web/$WEB_SYSTEM/*tpl
    fi
fi

# Rebuild web domains
for user in $($BIN/v-list-sys-users plain); do
    $BIN/v-rebuild-web-domains $user no
done


#----------------------------------------------------------#
#                       Vesta                              #
#----------------------------------------------------------#

# Restart web server
if [ "$restart" != 'no' ]; then
    $BIN/v-restart-web
    if [ $? -ne 0 ]; then
        exit $E_RESTART
    fi

    $BIN/v-restart-proxy
    if [ $? -ne 0 ]; then
        exit $E_RESTART
    fi
fi

# Delete tmpdir
rm -rf $tmpdir

exit
