#!/bin/sh

### PATH TO GENERATE TYPO3 TEMPLATE FROM
templatefrom=/var/www/clients/client1/web1/web/typo3/

### PATH TO DROP THE TYPO3 GENERATED TEMPLATE FOLDER
templateto=/var/www/typo3_template/



### NOTHING TO BE CHANGED BELOW HERE
templatefromconf=${templatefrom}typo3conf/localconf.php

typo3version=$(grep -i "compat_version" ${templatefromconf} | sed "s/\$TYPO3_CONF_VARS\['SYS'\]\['compat_version'\] = '$1/$1/g" | sed "s/'.*//g")

echo ''
echo '### GENERATE TEMPLATE IN' $templateto '###'
echo ''

read -p 'Please enter name of template folder[e.g. vorlage-v3]: ' templatefolder
echo "Folder name: $templatefolder"

echo 'copying ...'

### PUT VARIABLES INTO VARIABLE
foldercreated=${templateto}${templatefolder}-v${typo3version}-$(date +%d_%m_%Y-%H_%M)
localconf=${foldercreated}/typo3conf/localconf.php

mkdir $foldercreated
cp -Rf $templatefrom/* $foldercreated

echo ''
echo '### CLEAR DATABASE SETTINGS IN' $templateto$templatefolder '###'
echo ''

sed -i "s/\$typo_db_username.*;/\$typo_db_username = '';/g" ${localconf}
echo '# SET $typo_db_username'

sed -i "s/\$typo_db_password.*;/\$typo_db_password = '';/g" ${localconf}
echo '# SET $typo_db_password'

sed -i "s/\$typo_db =.*;/\$typo_db = '';/g" ${localconf}
echo '# SET $typo_db'

sed -i "s/\$typo_db_host.*;/\$typo_db_host = 'localhost';/g" ${localconf}
echo '# SET $typo_db_host'


mysql_user=$(grep -i "typo_db_username = " ${templatefromconf} | sed "s/\$typo_db_username = '$1/$1/g" | sed "s/'.*//g")
mysql_password=$(grep -i "typo_db_password = " ${templatefromconf} | sed "s/\$typo_db_password = '$1/$1/g" | sed "s/'.*//g")
mysqldbname=$(grep -i "typo_db = " ${templatefromconf} | sed "s/\$typo_db = '$1/$1/g" | sed "s/'.*//g")
mysql_host=$(grep -i "typo_db_host = " ${templatefromconf} | sed "s/\$typo_db_host = '$1/$1/g" | sed "s/'.*//g")

echo ''
echo '### EXPORT TEMPLATE DATABASE' $mysqldbname '###'

mysqldump $mysqldbname > ${foldercreated}/typo3conf/typo3_template-db.sql -u $mysql_user -p$mysql_password

echo ''
echo '### REMOVE deprecation*.log in' $foldercreated '###'

find $foldercreated -name deprecation*.log -delete

echo ''
echo '### DONE... CHECK TEMPLATE IN' $foldercreated '###'
