#!/usr/bin/env bash
set -euo pipefail

# Run this ON THE SERVER as root.
# Installs Apache + PHP + Composer + Node basics for Daneshyar.
# No passwords are stored here.

APP_DIR="${APP_DIR:-/var/www/daneshyar}"
PHP_VERSION="${PHP_VERSION:-8.3}"

apt-get update
apt-get install -y software-properties-common ca-certificates curl unzip git rsync

if ! apt-cache show "php${PHP_VERSION}-cli" >/dev/null 2>&1; then
  add-apt-repository -y ppa:ondrej/php
  apt-get update
fi

apt-get install -y \
  apache2 \
  "php${PHP_VERSION}" \
  "php${PHP_VERSION}-cli" \
  "php${PHP_VERSION}-common" \
  "php${PHP_VERSION}-mysql" \
  "php${PHP_VERSION}-mbstring" \
  "php${PHP_VERSION}-xml" \
  "php${PHP_VERSION}-curl" \
  "php${PHP_VERSION}-zip" \
  "php${PHP_VERSION}-gd" \
  "php${PHP_VERSION}-bcmath"

if ! command -v composer >/dev/null 2>&1; then
  curl -fsSL https://getcomposer.org/installer -o /tmp/composer-setup.php
  php /tmp/composer-setup.php --install-dir=/usr/local/bin --filename=composer
  rm -f /tmp/composer-setup.php
fi

if ! command -v node >/dev/null 2>&1; then
  curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
  apt-get install -y nodejs
fi

mkdir -p "$APP_DIR"
chown -R www-data:www-data "$APP_DIR"

cat >/etc/apache2/sites-available/daneshyar.conf <<APACHE
<VirtualHost *:80>
    ServerName 91.107.131.171
    DocumentRoot ${APP_DIR}/public

    <Directory ${APP_DIR}/public>
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog \${APACHE_LOG_DIR}/daneshyar_error.log
    CustomLog \${APACHE_LOG_DIR}/daneshyar_access.log combined
</VirtualHost>
APACHE

a2enmod rewrite headers
a2dissite 000-default.conf || true
a2ensite daneshyar.conf
systemctl enable apache2
systemctl reload apache2

echo "Server base setup complete."
echo "Upload the project to: $APP_DIR"
echo "Apache DocumentRoot: $APP_DIR/public"
