#!/bin/bash
set -e

DOMAIN="ads.barada.ir"
PROJECT_DIR="/root/telegram-ads"
WEB_DIR="/var/www/$DOMAIN"

echo "Updating system..."
apt-get update -qq

echo "Installing dependencies..."
DEBIAN_FRONTEND=noninteractive apt-get install -y apache2 php libapache2-mod-php certbot python3-certbot-apache

echo "Setting up web directory..."
mkdir -p $WEB_DIR
# Copy files, overwriting if exists
cp -r $PROJECT_DIR/* $WEB_DIR/

# Set permissions
chown -R www-data:www-data $WEB_DIR
chmod -R 755 $WEB_DIR

echo "Configuring Apache..."
# Move config file
cp $PROJECT_DIR/ads.barada.ir.conf /etc/apache2/sites-available/$DOMAIN.conf

# Enable site and modules
a2enmod rewrite
a2ensite $DOMAIN.conf
# Optional: disable default
# a2dissite 000-default.conf

systemctl reload apache2

echo "Obtaining SSL..."
# Try to obtain cert. If it fails (e.g. DNS not propagated), it shouldn't stop the script completely if we want to debug, but set -e is on.
# We will use || true to allow it to fail without crashing the script, so at least http works.
certbot --apache -d $DOMAIN --non-interactive --agree-tos -m admin@barada.ir --redirect || echo "SSL Certification failed. Check DNS settings."

echo "Deployment Complete!"
