#!/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 -eE
trap 'printf "\e[31m%s: %s\e[m\n" "Error downloading llxamp-install-pack!" $?' ERR

script_dir=$( cd -- "$( dirname -- $(realpath -e "${BASH_SOURCE[0]}") )" &> /dev/null && pwd )
script_name="$(basename ${BASH_SOURCE[0]})"
DISTRO=$(lsb_release -cs)
REPO=https://svnlliurexnet.gva.es/$DISTRO/llxamp-packages
TMPDIR="$1"
TMPDIR=${TMPDIR:=/tmp/llxamp-install-pack}
TMPDIR=$(realpath "$TMPDIR")
MD5=${MD5:=install-pack-$DISTRO.tar.zst.md5}
FILES=$(grep -v '#' /usr/lib/llxamp/files|grep -v '.md5')
CURL=$(which curl)
SED=$(which sed) 
MD5SUM=$(which md5sum)

path=/usr/lib/llxamp
source $path/environ-install-pack

mkdir -p "$TMPDIR"
if [ -z "$NOCHECKSOURCES" ];then
    $CURL -s "$REPO/$MD5" -o "$TMPDIR/$MD5"
    FILES=$($SED -nr 's|\s+|,|gp' "$TMPDIR/$MD5"|cut -d',' -f2)
fi
for file in $FILES; do
    if [ -e "$TMPDIR/$file" ]; then
        if [ -z "$NOCHECKSOURCES" ]; then
            true_md5=$(egrep "$file\$" "$TMPDIR/$MD5" |cut -d' ' -f1)
            md5=$($MD5SUM "$TMPDIR/$file"|cut -d' ' -f1)
            if [ "x$true_md5" == "x$md5" ]; then
                echo "Found $file"
            else
                echo Downloading "$file" into "$TMPDIR" ...
                $CURL --progress-bar "$REPO/$file" -o "$TMPDIR/$file"
            fi
        else
            echo "Found $file"
        fi
    else
        echo Downloading "$file" into "$TMPDIR" ...
        $CURL --progress-bar "$REPO/$file" -o "$TMPDIR/$file"
    fi
done
pushd "$TMPDIR" > /dev/null 2>&1
$MD5SUM -c "$TMPDIR/$MD5" >/dev/null 2>&1 && echo Download into $TMPDIR successful || echo Download failed
popd > /dev/null 2>&1
exit 0