#!/bin/bash

# Copyright (C) 2023 M.Angel Juan
#
# This file is part of LLXAMP.
#
# LLXAMP is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# LLXAMP is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with LLXAMP.  If not, see <http://www.gnu.org/licenses/>.

set -e

here=$(realpath .)

output=
for param in "$@"; do
    case "$param" in
        -o*)
            shift
            output=$1
        ;;
        -h*)
            show_help
            exit 0
        ;;
    esac
done

basepath=@@LLXAMP_BASEPATH@@
dirs="httpd/conf httpd/htdocs php/lib/php.ini*"
filename=llxamp-backup

tmp=$(mktemp -d)

cd $tmp

export $(llxamp-status -m)
if [ "x$MYSQL_RUNNING" == "x1" ];then
    llxamp-stop-mysql
    sleep 1
    llxamp-kill-mysql
fi

@@LLXAMP_BASEPATH@@/mysql/bin/mysqld --defaults-file=@@LLXAMP_BASEPATH@@/mysql/conf/my.cnf --skip-grant-tables > /dev/null 2>&1 &
while ! @@LLXAMP_BASEPATH@@/mysql/bin/mysql --defaults-file=@@LLXAMP_BASEPATH@@/mysql/conf/my.cnf --user=root -e 'status' >/dev/null 2>&1; do
    sleep 1;
done;

llxamp-mysqldump --all-databases --add-drop-database --add-drop-table --add-locks --all-tablespaces --comments --complete-insert --dump-date --extended-insert --flush-logs --flush-privileges --routines --triggers --user root > backup-mysql.sql

kill $(cat $HOME/llxamp/mysql/temp/mysql.pid)

if [ "x$MYSQL_RUNNING" == "x1" ];then
    llxamp-start-mysql
fi

cd $basepath

tar -c -f $tmp/$filename.tar -C $basepath $dirs
tar --append -f $tmp/$filename.tar -C $tmp backup-mysql.sql

cd $tmp

gzip -9 $tmp/$filename.tar

if [ -n "$output" ]; then
    cd $here
    d=$(dirname "$output")
    f=$(basename "$output")
    mkdir -p "$d"
    mv $tmp/$filename.tar.gz "$d"/"$f"
    echo "Backup saved in '$d/$f'"
else
    echo "Backup saved in '$tmp/$filename.tar.gz'"
fi
