#!/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/>.

export TEXTDOMAIN="llxamp-cmdline"

source /usr/lib/llxamp/environ-cmdline

file_pack=${file_pack:=$INSTALL_PACK_DIR/$PACKNAME}
file_pack=${file_pack:=/tmp/llxamp-install-pack/install-pack.tgz}

target=${target:=$TARGET_DIR}
target=${target:=$HOME/llxamp}

help_menu(){
    echo
    echo $(gettext "Usage"):
    echo
    echo "$program [-p <$(gettext "file_pack")>] [-t <$(gettext "target")>] [-f] [-h]"
    echo "  -f: $(gettext "force overwrite target")"
    echo "  -h: $(gettext "this help")"
    echo "  $(gettext "defaults"):"
    echo "    <$(gettext "file_pack")>: $file_pack"
    echo "    <$(gettext "target")>: $target"
    echo
}

error_menu(){
    echo
    echo $(gettext "Error") $1
    help_menu
    exit 1
}

execute(){
    $@
    if [ $? -ne 0 ]; then
        echo "$(gettext "Error executing") '$@', $(gettext "aborting operation")"
        exit 1
    fi
}

execute_to_tempfile(){
    tmpfile=$(mktemp)
    $@ > $tmpfile
    if [ $? -ne 0 ]; then
        echo "$(gettext "Error executing") '$@', $(gettext "aborting operation")"
        exit 1
    fi
    echo "$tmpfile"
}

execute_silent(){
    $@ >/dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo "$(gettext "Error executing") '$@', $(gettext "aborting operation")"
        exit 1
    fi
}

get_versions(){
    APACHE_VERSION=
    MYSQL_VERSION=
    PHP_VERSION=
    PHPMYADMIN_VERSION=
    HAVE_MARIADB=
    HAVE_MYSQL=
    APACHE_VERSION=$(LD_LIBRARY_PATH="$DECOMPRESSED_PACK_DIR/httpd/lib/:$LD_LIBRARY_PATH" $DECOMPRESSED_PACK_DIR/httpd/bin/httpd -v|grep -i version|cut -d/ -f2|cut -d' ' -f1)
    if [ -d "$DECOMPRESSED_PACK_DIR/mariadb" ]; then
        HAVE_MARIADB='yes'
        MYSQL_VERSION=$($DECOMPRESSED_PACK_DIR/mariadb/bin/mariadbd --version|awk '{print $3}'|cut -d- -f1)
    fi
    if [ -d "$DECOMPRESSED_PACK_DIR/mysql" ]; then
        HAVE_MYSQL='yes'
        MYSQL_VERSION=$($DECOMPRESSED_PACK_DIR/mysql/bin/mysqld --version|awk '{print $3}'|cut -d- -f1)
    fi
    PHP_VERSION=$($DECOMPRESSED_PACK_DIR/php/bin/php -v|head -1|awk '{print $2}')
    PHPMYADMIN_VERSION=$(head -10 $DECOMPRESSED_PACK_DIR/httpd/htdocs/phpMyAdmin/README|grep -i version|awk '{print $2}')
    echo "APACHE version $APACHE_VERSION"
    echo "MARIADB version $MYSQL_VERSION"
    echo "PHP version $PHP_VERSION"
    echo "PHPMYADMIN version $PHPMYADMIN_VERSION"
}

make_change_text(){
    echo $(gettext "Patching text files")
    export LC_ALL=C
    components="httpd php"
    [ ! -e "$rptarget" ] && error_menu "$(gettext "invalid target")"
    pushd $rptarget >/dev/null

    for component in $components; do
        found=$(execute egrep -Ilor "$TAG" $component)
        if [ $? -eq 0 -a -n "$found" ];then
            found=($(echo $found |xargs -n1 |sort|uniq))
            for file in ${found[@]}; do
                cp "$file" "$file.pre-change"
                sed -r "s|$TAG|$rptarget|g" "$file.pre-change" > "$file"
            done
        fi
    done
    find $rptarget -name '*.pre-change' -exec rm {} \;
    popd > /dev/null
    export LC_ALL=
}

make_change_bin(){
    echo $(gettext "Patching binary files")
    export LC_ALL=C
    components="httpd php"
    [ ! -e "$rptarget" ] && export LC_ALL="" && error_menu "$(gettext "invalid target")"
    pushd $rptarget >/dev/null
    declare -a found_bins_with_tag
    for component in $components; do
        found_bins=$(execute find $component -type f -not \( -name '*.png' -o -name '*.gif' -o -name '*.mo' -o -name '*.z' -o -name '*.ico' \) -exec grep . -IL "{}" \;)
        if [ $? -eq 0 -a -n "$found_bins" ];then
            found_bins=($(echo $found_bins |xargs -n1 |sort|uniq))
            for file in ${found_bins[@]}; do
                found_tag=$(grep -ol "$TAG" "$file")
                if [ -n "$found_tag" ]; then
                    found_bins_with_tag+=($found_tag)
                    if [ -n "$found_tag" ];then
                        execute python3 $script_dir/patch.py $rptarget/$file $TAG $rptarget
                    fi
                fi
            done
        fi
    done

    for file in ${found_bins_with_tag[@]}; do
        path=""
        path=$((chrpath -l "$file" 2>/dev/null || true)|grep "$TAG"|sed -nr "s|.*RUNPATH=$TAG(.*)|\1|p")
        if [ -n "$path" ]; then
            execute chrpath -r "$rptarget$path" $file >/dev/null
        fi
    done

    popd > /dev/null
    export LC_ALL=
}

write_httpd_conf(){
    [ ! -e "$rptarget" ] && error_menu "$(gettext "invalid target")"
    sed -r -e "s|@@LLXAMP_BASEPATH@@|$rptarget|g" -e "s|@@LLXAMP_PORT@@|$DEFAULT_PORT|g" -e "s|@@LLXAMP_USER@@|$(whoami)|g" -e "s|@@LLXAMP_SERVERNAME@@|$(hostname)|g" "$TEMPLATES_DIR"/httpd.conf > $rptarget/httpd/conf/httpd.conf
    sed -r -e "s|@@LLXAMP_BASEPATH@@|$rptarget|g" -e "s|@@LLXAMP_SSL_PORT@@|$DEFAULT_SSL_PORT|g" -e "s|@@LLXAMP_USER@@|$(whoami)|g" -e "s|@@LLXAMP_SERVERNAME@@|$(hostname)|g" "$TEMPLATES_DIR"/httpd-ssl.conf > $rptarget/httpd/conf/httpd-ssl.conf
}

include_php_samples(){
    [ ! -e "$rptarget" ] && error_menu "invalid target"
    echo $(gettext "Including PHP sample pages")
    cp "$TEMPLATES_DIR"/db.php $rptarget/httpd/htdocs/
    cp "$TEMPLATES_DIR"/info.php $rptarget/httpd/htdocs/
}

configure_mysql(){
    [ ! -e "$rptarget" ] && error_menu "invalid target"
    echo $(gettext "Configuring MariaDB")
    if [ -n "$HAVE_MARIADB" ];then
        suffix=mariadb
    else
        suffix=mysql
    fi

    mkdir -p $rptarget/$suffix/{conf,temp,var/{mysql,log}}
    if [ -n "$HAVE_MARIADB" ];then
        cp -R $TEMPLATES_DIR/mariadb-conf/* $rptarget/mariadb/conf/
        for fileconf in $(find "$rptarget/mariadb/conf" -type f); do
            cp $fileconf $fileconf.pre-change
            sed -r -e "s|@@LLXAMP_BASEPATH@@|$rptarget|g" -e "s|@@LLXAMP_USER@@|$(whoami)|g"  $fileconf.pre-change > $fileconf
        done
        find "$rptarget/mariadb/conf" -type f -name '*.pre-change' -exec rm {} \;
    else
        sed -r "s|@@LLXAMP_BASEPATH@@|$rptarget|g" "$TEMPLATES_DIR"/my.cnf > $rptarget/mysql/conf/my.cnf
    fi
}

configure_mysql2(){
    [ ! -e "$rptarget" ] && error_menu "invalid target"
    if [ -n "$HAVE_MARIADB" ];then
        suffix=mariadb
        installdb=mariadb-install-db
        user=$(whoami)
    else
        suffix=mysql
        installdb=mysql_install_db
        user=root
    fi
    echo $(gettext "Installing initial database")
    execute_silent $rptarget/$suffix/scripts/$installdb --basedir=$rptarget/$suffix --datadir=$rptarget/$suffix/data --no-defaults --user=$(whoami)
    echo $(gettext "Starting database")
    execute_silent bash $startup_scripts/llxamp-start-mysql
    while ! $rptarget/$suffix/bin/$suffix --defaults-file=$rptarget/$suffix/conf/my.cnf --user=$user -e 'status' > /dev/null 2>&1; do
        sleep 1
    done
    echo $(gettext "Creating test table")
    execute_silent $rptarget/$suffix/bin/$suffix --defaults-file=$rptarget/$suffix/conf/my.cnf --user=$user < "$TEMPLATES_DIR"/create_table.sql
    echo $(gettext "Securing Mysql installation")
    execute_silent $rptarget/$suffix/bin/$suffix --defaults-file=$rptarget/$suffix/conf/my.cnf --user=$user < "$TEMPLATES_DIR"/$suffix-secure_installation.sql
    echo $(gettext "Stopping database")
    execute bash $startup_scripts/llxamp-stop-mysql
    truncate -s 0 $rptarget/$suffix/var/log/*log
}

write_start_scripts(){
    [ ! -e "$rptarget" ] && error_menu "invalid target"
    [ ! -e "$startup_scripts" ] && mkdir -p "$startup_scripts"

    echo $(gettext "Writting start/stop scripts into") "$rptarget"

    for script in "$TEMPLATES_DIR"/llxamp-*; do
        scriptname="$startup_scripts/$(basename $script)"
        sed -r -e "s|@@LLXAMP_BASEPATH@@|$rptarget|g" -e "s|@@LLXAMP_PORT@@|$DEFAULT_PORT|g" -e "s|@@LLXAMP_SSL_PORT@@|$DEFAULT_SSL_PORT|g" "$script" > $scriptname
        chmod +x "$scriptname"
        echo "[+] $scriptname"
    done
}

create_target_dir(){
    if [ -n "$HAVE_MARIADB" ];then
        suffix=mariadb
    else
        suffix=mysql
    fi
    pkill -9 -f httpd > /dev/null 2>&1
    pkill -9 -f $suffix > /dev/null 2>&1
    if [ ! -e "$rptarget" ]; then
        mkdir -p "$rptarget" ||  error_menu "$(gettext "Invalid parameter") '$target'"
    fi
    mkdir -p $HOME/.llxamp/{work,upper}
    if [ -e "$rptarget/mysql/data" ]; then
        rm -rf "$rptarget/mysql/data"
    fi
}

test_install_pack(){
    if [ -n "$HAVE_MARIADB" ];then
        suffix=mariadb
    else
        suffix=mysql
    fi
    need="build-tag httpd php mysql httpd/htdocs/phpMyAdmin"
    [ ! -e "$rpfile_pack" ] && error_menu "$(gettext "invalid install-pack")"
    echo Testing archive "$rpfile_pack"
    tmpfile=$(execute_to_tempfile tar -ztf "$rpfile_pack")
    sed -r 's|^[.]/(.*)|\1|g' $tmpfile > $tmpfile.new
    for n in $need; do
        if grep -s $n $tmpfile.new > /dev/null 2>&1; then
            echo "$(basename $n) $(gettext "found!")"
        else
            error_menu "$(basename $n) $(gettext "not found!")"
        fi
    done
}

decompress_pack(){
    #[ ! -e "$rptarget" -o ! -e "$rpfile_pack" ] && error_menu "invalid target or install-pack"
    [ ! -e "$rptarget" -o ! -e "$PACK_DIR" ] && error_menu "invalid target or install-pack"
    # echo "Decompressing archive into '$rptarget'"
    # execute tar -zxf "$rpfile_pack" -C "$rptarget"
    echo "$(gettext "Mounting archive into") '$rptarget' $(gettext "with copy-on-write")"
    mounted=$(findmnt -l -o TARGET | grep "$rptarget")
    if [ -n "$mounted" ];then
        echo "$(gettext "Remount needed on"): '$rptarget'"
        echo "$(gettext "Killing procs using") '$rptarget'"
        pids=$(lsof -u $(id -u) 2>/dev/null |grep "$HOME/llxamp"|awk '{print $2}'|sort|uniq|xargs)
        if [ -n "$pids" ]; then
            echo "$(gettext "Detected pids") $pids"
            kill -9 $pids
        fi
        # Too aggresive !
        # fuser -mk "$rptarget" > /dev/null 2>&1
        sleep 2
        echo "$(gettext "Mounting") '$rptarget'"
        fusermount -uz "$rptarget"
        sleep 2
        [ -e "$HOME/.llxamp/upper" ] && echo $(gettext "Removing previous cow") && rm -rf $HOME/.llxamp/upper
        mkdir -p $HOME/.llxamp/upper
    fi
    mounted=$(findmnt -l -o TARGET | grep "$rptarget")
    if [ -z "$mounted" ];then
        set -e
        if [ -e "$PACK_DIR" -a -e "$HOME/.llxamp/upper" -a -e "$HOME/.llxamp/work" ]; then
            [ -e "$HOME/.llxamp/upper" ] && echo $(gettext "Removing previous cow") && rm -rf $HOME/.llxamp/upper && mkdir -p $HOME/.llxamp/upper
            fuse-overlayfs -olowerdir=$PACK_DIR,upperdir=$HOME/.llxamp/upper,workdir=$HOME/.llxamp/work,squash_to_uid=$(id -u),squash_to_gid=$(id -g) "$rptarget" >/dev/null 2>&1
        else
            echo $(gettext "Can't mount overlay")
            exit 1
        fi
        set +e
    fi
}

read_tag(){
    [ ! -e "$rptarget" ] && error_menu "$(gettext "invalid target")"
    echo "$(gettext "Reading tag")"
    TAG=$(cat "$rptarget/build-tag")
    [ -z "$TAG" ] && error_menu "$(gettext "Empty tag")"
    rm "$rptarget/build-tag"
}

configure_user_path(){
    echo "$(gettext "Configuring user path")"
    if ! grep -s 'LLXAMP_PATH' $HOME/.bashrc > /dev/null 2>&1; then
        echo -e "\nLLXAMP_PATH=\"$startup_scripts\"\n" >> $HOME/.bashrc
        echo -e '\nexport PATH="$LLXAMP_PATH:$PATH"\n' >> $HOME/.bashrc
    fi
}

gen_openssl_certs(){
    [ ! -e "$rptarget" ] && error_menu "$(gettext "invalid target")"
    echo Generating OpenSSL certificates
    execute_silent openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout "$rptarget"/httpd/conf/server.key -out "$rptarget"/httpd/conf/server.crt -subj "/C=XX/ST=StateName/L=CityName/O=CompanyName/OU=CompanySectionName/CN=CommonNameOrHostname"
}

fix_missing_php_ini(){
    [ ! -e "$rptarget" ] && error_menu "$(gettext "invalid target")"
    oFS=$IFS
    IFS=' '
    php_files="php.ini-development php.ini-production"
    main_file="php.ini-development"
    for inifile in $php_files; do
        if [ ! -e "$rptarget/php/lib/$inifile" ]; then
            if [ -e "$TEMPLATES_DIR/$inifile" ]; then
                echo Fixing "$rptarget/php/lib/$inifile"
                cp "$TEMPLATES_DIR/$inifile" "$rptarget/php/lib/$inifile"
            fi
        fi
    done
    if [ ! -e "$rptarget/php/lib/php.ini" ]; then
        if [ -e "$TEMPLATES_DIR/$main_file" ]; then
            echo Fixing "$rptarget/php/lib/php.ini"
            cp "$TEMPLATES_DIR/$main_file" "$rptarget/php/lib/php.ini"
        fi
    fi
    IFS=$oFS
}

print_info(){
    echo $(gettext "Finished!")
    echo
    echo $(gettext "Start services with:")
    echo '  $ llxamp-start'
    echo $(gettext "View initial page served with:")
    echo '  $ llxamp-open-browser'
    echo $(gettext "View with SSL phpMyAdmin initial page with:")
    echo '  $ llxamp-open-browser-ssl /phpMyAdmin/index.php  #(default_username=root, default_root_password=root)'
    echo $(gettext "Stop services with:")
    echo '  $ llxamp-stop'
    echo $(gettext "View more scripts pressing bash autocompletion keys:")
    echo '  $ llxamp<TAB_KEY><TAB_KEY>'
    echo
}
# MAIN EXECUTION

script_dir=$( cd -- "$( dirname -- $(realpath -e "${BASH_SOURCE[0]}") )" &> /dev/null && pwd )
program=$(basename "${BASH_SOURCE[0]}")
args="$@"
nargs=$#
TEMPLATES_DIR=${TEMPLATES_DIR:=$script_dir/templates}
PACK_DIR=${PACK_DIR:=/usr/lib/llxamp/pack}
forced=
while test -n "$1"; do
    param=$1
    case "$param" in
        -p)
            shift
            [ -n "$1" -a "${1:0:1}" != "-" -a -f "$1" ] && file_pack="$1" || help_menu
        ;;
        -t)
            shift
            [ -n "$1" -a "${1:0:1}" != "-" ] && target="$1" || help_menu
        ;;
        -f)
            forced="yes"
        ;;
        -h)
            help_menu
            exit 0
        ;;
        *)
            help_menu
            exit 1
        ;;
    esac
    shift
done

file_pack=${file_pack:=$INSTALL_PACK_DIR/$PACKNAME}
file_pack=${file_pack:=/tmp/llxamp-install-pack/install-pack.tgz}
rpfile_pack=
if [ -e "$file_pack" ]; then
    rpfile_pack=$(execute realpath "$file_pack")
fi

target=${target:=$TARGET_DIR}
target=${target:=$HOME/llxamp}
rptarget=$(execute realpath "$target")

if [ -e "$rptarget" -a -z "$forced" ]; then
    error_menu "'$rptarget' $(gettext "exists"), $(gettext "must be non-existent directory")"
fi

startup_scripts="$rptarget/scripts"

if [ ! -e "/usr/lib/llxamp/pack" ]; then
    if [ -z "$rpfile_pack" -o ! -e "$rpfile_pack" ]; then
        llxamp-download-install-pack || error_menu "$(gettext "Invalid pack file")"
        [ -e "/tmp/llxamp-install-pack/install-pack.tgz" ] && rpfile_pack="/tmp/llxamp-install-pack/install-pack.tgz"
    fi
fi

get_versions
#test_install_pack
create_target_dir
decompress_pack
read_tag
make_change_text
make_change_bin
write_httpd_conf
include_php_samples
configure_mysql
write_start_scripts
configure_mysql2
configure_user_path
gen_openssl_certs
fix_missing_php_ini
print_info

source $HOME/.bashrc
