#!/bin/bash

clear
echo "=== Установка phpMyAdmin + MariaDB + Apache2 + Защита ==="
echo

read -p "Введите домен для phpMyAdmin (например: pma.example.com): " PMA_DOMAIN < /dev/tty
echo
echo "Убедитесь, что A-запись для $PMA_DOMAIN указывает на IP сервера."
read -p "Продолжить? (y/n): " REPLY < /dev/tty
if [[ ! "$REPLY" =~ ^[Yy]$ ]]; then
    echo "Отмена."
    exit 1
fi

echo "Обновление системы..."
apt-get update -y
apt-get upgrade -y

echo "Установка Apache, PHP, MariaDB, Certbot..."
apt-get install -y apache2 mariadb-server php php-mbstring php-zip php-gd php-json php-curl php-mysql wget unzip curl certbot python3-certbot-apache apache2-utils fail2ban

echo "Ожидание запуска MariaDB..."
until mysqladmin ping &>/dev/null; do
    echo "  → MariaDB ещё не готова, жду..."
    sleep 2
done

echo "MariaDB готова!"

# Генерация данных
DB_NAME="mydb"
DB_USER="user_$(tr -dc 'a-z0-9' </dev/urandom | head -c 6)"
DB_PASS=$(openssl rand -base64 16)

CONTROL_USER="pma_$(tr -dc 'a-z0-9' </dev/urandom | head -c 6)"
CONTROL_PASS=$(openssl rand -base64 16)

PMADB="phpmyadmin"

# Basic Auth user/pass
BASIC_USER="admin_$(tr -dc 'a-z0-9' </dev/urandom | head -c 4)"
BASIC_PASS=$(openssl rand -base64 12)
AUTH_FILE="/etc/phpmyadmin/.htpasswd"

echo "Создание базы данных и пользователей..."

mysql -u root <<EOF
CREATE DATABASE $DB_NAME;
CREATE USER '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASS';
GRANT ALL PRIVILEGES ON $DB_NAME.* TO '$DB_USER'@'localhost';

CREATE DATABASE IF NOT EXISTS $PMADB;
CREATE USER IF NOT EXISTS '$CONTROL_USER'@'localhost' IDENTIFIED BY '$CONTROL_PASS';
GRANT ALL PRIVILEGES ON $PMADB.* TO '$CONTROL_USER'@'localhost';

FLUSH PRIVILEGES;
EOF

echo "Установка phpMyAdmin..."
wget -q https://www.phpmyadmin.net/downloads/phpMyAdmin-latest-all-languages.zip -O /tmp/pma.zip
unzip -q /tmp/pma.zip -d /usr/share/
mv /usr/share/phpMyAdmin-* /usr/share/phpmyadmin

mkdir -p /usr/share/phpmyadmin/tmp
chmod 777 /usr/share/phpmyadmin/tmp

cp /usr/share/phpmyadmin/config.sample.inc.php /usr/share/phpmyadmin/config.inc.php

# Настройка controluser
sed -i "s/\['controluser'\] = '';/['controluser'] = '$CONTROL_USER';/" /usr/share/phpmyadmin/config.inc.php
sed -i "s/\['controlpass'\] = '';/['controlpass'] = '$CONTROL_PASS';/" /usr/share/phpmyadmin/config.inc.php
sed -i "s/\['pmadb'\] = '';/['pmadb'] = '$PMADB';/" /usr/share/phpmyadmin/config.inc.php

# Blowfish secret
BLOWFISH=$(tr -dc 'a-zA-Z0-9' </dev/urandom | head -c 32)
sed -i "s/\['blowfish_secret'\] = '';/['blowfish_secret'] = '$BLOWFISH';/" /usr/share/phpmyadmin/config.inc.php

# Импорт таблиц хранилища
echo "Импорт таблиц phpMyAdmin Storage..."
mysql -u root $PMADB < /usr/share/phpmyadmin/sql/create_tables.sql

# Создание Basic Auth
echo "Настройка Basic Auth (двойной пароль)..."
mkdir -p /etc/phpmyadmin
htpasswd -cb "$AUTH_FILE" "$BASIC_USER" "$BASIC_PASS"

# Apache vhost
cat >/etc/apache2/sites-available/phpmyadmin.conf <<EOF
<VirtualHost *:80>
    ServerName $PMA_DOMAIN
    DocumentRoot /usr/share/phpmyadmin

    <Directory /usr/share/phpmyadmin>
        AllowOverride All

        AuthType Basic
        AuthName "Restricted Area"
        AuthUserFile $AUTH_FILE
        Require valid-user
    </Directory>
</VirtualHost>
EOF

a2dissite 000-default
a2ensite phpmyadmin
a2enmod rewrite
systemctl reload apache2

echo "Получение SSL сертификата..."
certbot --apache -d "$PMA_DOMAIN" --non-interactive --agree-tos -m admin@$PMA_DOMAIN

# Fail2Ban защита для phpMyAdmin
echo "Настройка Fail2Ban..."

cat >/etc/fail2ban/filter.d/phpmyadmin.conf <<EOF
[Definition]
failregex = <HOST> -.*"(GET|POST).*phpmyadmin"
ignoreregex =
EOF

cat >/etc/fail2ban/jail.d/phpmyadmin.local <<EOF
[phpmyadmin]
enabled = true
port = http,https
filter = phpmyadmin
logpath = /var/log/apache2/access.log
maxretry = 5
bantime = 3600
EOF

systemctl restart fail2ban

# Запрет XML-RPC
echo "Запрет XML-RPC..."
cat >> /etc/apache2/apache2.conf <<EOF

# Block XML-RPC attacks
<Files "xmlrpc.php">
    Require all denied
</Files>
EOF

systemctl reload apache2

echo
echo "=== УСТАНОВКА И ЗАЩИТА phpMyAdmin ЗАВЕРШЕНА ==="
echo
echo "Доступ к phpMyAdmin: https://$PMA_DOMAIN"
echo
echo "Данные MariaDB:"
echo "  База данных: $DB_NAME"
echo "  Пользователь: $DB_USER"
echo "  Пароль: $DB_PASS"
echo
echo "Controluser phpMyAdmin:"
echo "  Пользователь: $CONTROL_USER"
echo "  Пароль: $CONTROL_PASS"
echo
echo "Basic Auth (двойной пароль):"
echo "  Логин: $BASIC_USER"
echo "  Пароль: $BASIC_PASS"
echo
echo "Fail2Ban включён, XML-RPC заблокирован."
echo
