#!/bin/bash

# Usage:
# bash <(curl -s https://scripts.justman10000.de/installers/mariadb.sh)

apt install libncurses5 -y
adduser --gecos --disabled-login --disabled-password --no-create-home mysql

echo "You can give an custom version!"
echo "Submit the version without the mariadb- prefix (only the numbers itself)!"
echo "You can also leave this blank! Then the newest version will be installed..."
echo "Supported versions are:"
sleep 4
curl -s https://archive.mariadb.org/ | grep -oP "mariadb-\d+\.\d+\.\d+" | sort -rV | uniq
read -p 'Version: ' cstv

! [[ $cstv ]] && cstv='\d+\.\d+\.\d+'

if [[ -d /usr/local/mariadb ]]; then
    reset
    echo "MariaDB is already installed! Reinstall? [y/N]"
    read reinstall

    [[ $reinstall == "y" ]] && rm -rf /usr/local/mariadb && kill $(lsof -i:3306 | grep -ioP '[0-9]{5}' | head -n 1)
fi

# reset

#prev='-preview'
version=$(curl -s https://archive.mariadb.org/ | grep -oP "mariadb-$cstv" | sort -rV | head -n 1)
url="https://archive.mariadb.org/$version/bintar-linux-systemd-x86_64/$version$prev-linux-systemd-x86_64.tar.gz"

[[ $(wget --spider -S $url 2>&1 | awk '/HTTP\//{print $2; exit}') != 200 ]] && echo Test && exit 1

wget $url

gunzip $version-linux-systemd-x86_64.tar.gz
tar xvf $version-linux-systemd-x86_64.tar
mv $version-linux-systemd-x86_64 /usr/local/mariadb
rm -r *.tar

ln -fs /usr/local/mariadb/bin/* /usr/bin

/usr/local/mariadb/scripts/mariadb-install-db --basedir=/usr/local/mariadb --datadir=/usr/local/mariadb/data
chmod -R 777 /usr/local/mariadb
ln -fs /usr/local/mariadb /usr/local/mysql
/usr/local/mariadb/bin/mariadbd-safe --datadir="/usr/local/mariadb/data" --pid-file="/usr/local/mariadb/data/`uname -n`.pid" "$@" &

ln -fs /usr/local/mariadb/data/`uname -n`.err /var/log/mariadb.log

mkdir /run/mysqld
ln -fs /tmp/mysql.sock /run/mysqld/mysqld.sock

sleep 2

cat << EOF >> /root/.bashrc

export MYSQLCLIENT_CFLAGS="-I/usr/local/mariadb/include/mysql -I/usr/local/mariadb/include/mysql/mysql"
export MYSQLCLIENT_LDFLAGS="-L/usr/local/mariadb/lib/ -lmariadb"
EOF

# reset

read -p 'New database user: ' user
read -p 'Password of the new database user: ' pass

! [[ $pass ]] && pass=$(grs)

mariadb << EOF
CREATE USER $user@localhost IDENTIFIED BY '$pass';
GRANT ALL PRIVILEGES ON *.* TO $user@localhost WITH GRANT OPTION;
CREATE USER $user IDENTIFIED BY '$pass';
GRANT ALL PRIVILEGES ON *.* TO $user WITH GRANT OPTION;
EOF

cat << EOF
Username: $user
Password: $pass
EOF

mariadb-secure-installation