#!/usr/bin/env bash
set -Eeuo pipefail
[[ $EUID -eq 0 ]] || { echo 'Bitte als root ausführen.'; exit 1; }
source /etc/os-release
[[ $ID == debian || $ID == ubuntu ]] || { echo 'Nur Debian/Ubuntu.'; exit 1; }
SRC=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
DEST=/var/www/fonics-shop
read -rp 'Shop-Domain (ohne https://): ' DOMAIN
[[ $DOMAIN =~ ^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?$ && $DOMAIN == *.* && ${#DOMAIN} -lt 254 ]] || exit 1
read -rp 'Webserver [apache/nginx]: ' SERVER
[[ $SERVER == apache || $SERVER == nginx ]] || exit 1
[[ ! -e $DEST && ! -e /etc/apache2/sites-available/fonics-shop.conf && ! -e /etc/nginx/sites-available/fonics-shop.conf ]] || { echo 'Ziel oder Konfiguration existiert. Abbruch ohne Überschreiben.'; exit 1; }
if command -v ss >/dev/null && ss -ltnH '( sport = :80 or sport = :443 )' | grep -q .; then echo 'Webserver-Port bereits belegt. Manuelle Einrichtung erforderlich.'; exit 1; fi
read -rp 'Pakete installieren und neuen Shop einrichten? [JA]: ' OK
[[ $OK == JA ]] || exit 1
apt-get update
apt-get install -y php-cli php-mysql php-curl php-mbstring php-xml php-zip php-gd mariadb-server composer openssl cron rsync
php -r 'exit(PHP_VERSION_ID>=80300?0:1);' || { echo 'PHP 8.3+ nicht aus konfigurierten Paketquellen verfügbar. Geeignete Quellen manuell einrichten.'; exit 1; }
if [[ $SERVER == apache ]]; then apt-get install -y apache2 libapache2-mod-php; else apt-get install -y nginx php-fpm; fi
systemctl enable --now mariadb cron
DB=fonics_shop; DBUSER=fonics_shop
if mariadb -Nse "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='$DB'" | grep -q . || mariadb -Nse "SELECT User FROM mysql.user WHERE User='$DBUSER'" | grep -q .; then echo 'Datenbank oder Benutzer existiert. Abbruch.'; exit 1; fi
DBPASS=$(openssl rand -hex 24); KEY=$(openssl rand -hex 32)
mkdir -m 0755 "$DEST"; rsync -a --exclude=config/local.php --exclude=config/setup.key --exclude=config/install.lock "$SRC/" "$DEST/"
cd "$DEST"; COMPOSER_ALLOW_SUPERUSER=1 composer install --no-dev --prefer-dist --no-interaction --no-plugins --no-scripts
mariadb -e "CREATE DATABASE $DB CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; CREATE USER '$DBUSER'@'localhost' IDENTIFIED BY '$DBPASS'; GRANT ALL PRIVILEGES ON $DB.* TO '$DBUSER'@'localhost';"
chown -R root:www-data "$DEST"; chmod -R u=rwX,g=rX,o= "$DEST"; chmod 0755 "$DEST"; chown -R www-data:www-data config storage public/media; chmod 0750 config storage public/media
printf '%s\n' "$KEY" > config/setup.key; chown www-data:www-data config/setup.key; chmod 0600 config/setup.key
if [[ $SERVER == apache ]]; then
  sed "s/SHOP_DOMAIN/$DOMAIN/g" deploy/apache.conf > /etc/apache2/sites-available/fonics-shop.conf
  a2enmod rewrite; a2ensite fonics-shop.conf; apache2ctl configtest; systemctl reload apache2
else
  VER=$(php -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;'); SOCKET="php${VER}-fpm.sock"
  [[ -S /run/php/$SOCKET ]] || { echo 'Passenden PHP-FPM-Dienst prüfen.'; exit 1; }
  sed -e "s/SHOP_DOMAIN/$DOMAIN/g" -e "s/PHP_FPM_SOCKET/$SOCKET/g" deploy/nginx.conf > /etc/nginx/sites-available/fonics-shop.conf
  ln -s /etc/nginx/sites-available/fonics-shop.conf /etc/nginx/sites-enabled/fonics-shop.conf; nginx -t; systemctl reload nginx
fi
read -rp 'SSL mit Certbot einrichten (DNS muss auf den Server zeigen)? [ja/nein]: ' SSL
if [[ $SSL == ja ]]; then
  apt-get install -y certbot "python3-certbot-$SERVER"; certbot "--$SERVER" -d "$DOMAIN" --redirect
fi
printf '%s\n' '*/5 * * * * www-data test ! -f /var/www/fonics-shop/config/local.php || /usr/bin/php /var/www/fonics-shop/cron/mail.php >> /var/www/fonics-shop/storage/logs/cron.log 2>&1' > /etc/cron.d/fonics-shop
chmod 0644 /etc/cron.d/fonics-shop
printf 'Installation vorbereit. HTTPS zuerst prüfen!\nURL: https://%s/install/\nDB: %s\nDB-User: %s\nDB-Passwort: %s\nSetup-Schlüssel: %s\n' "$DOMAIN" "$DB" "$DBUSER" "$DBPASS" "$KEY"
