#!/bin/bash
set -Eeuo pipefail

DOMAIN="westonbatemanbyu.4hx.net"
GITHUB_REPO_URL="https://github.com/BYU-ITC-210-Students/Lab-2B-wbateman314.git"
CERTBOT_EMAIL="wesb314@byu.edu"

# The repository will be cloned to /var/www/Lab-2B and linked as /var/www/html.
REPO_DIR_NAME="Lab-2B"
WEB_ROOT="/var/www"
HTML_LINK="${WEB_ROOT}/html"
SITE_NAME="it210_lab.conf"
SITE_DIR="/etc/apache2/sites-available"

if [[ "${EUID}" -eq 0 ]]; then
    RUN_USER="${SUDO_USER:-root}"
else
    RUN_USER="${SUDO_USER:-${USER}}"
fi
RUN_GROUP="$(id -gn "$RUN_USER")"
REPO_PATH="${WEB_ROOT}/${REPO_DIR_NAME}"

echo "Setting up Apache for ${DOMAIN}"
echo "Using repository: ${GITHUB_REPO_URL}"
echo "Running filesystem operations as: ${RUN_USER}:${RUN_GROUP}"

# Update, upgrade, and install packages

if [[ "${EUID}" -eq 0 ]]; then
    RUN_USER="${SUDO_USER:-root}"
else
    RUN_USER="${SUDO_USER:-${USER}}"
fi
RUN_GROUP="$(id -gn "$RUN_USER")"
REPO_PATH="${WEB_ROOT}/${REPO_DIR_NAME}"

echo "Setting up Apache for ${DOMAIN}"
echo "Using repository: ${GITHUB_REPO_URL}"
echo "Running filesystem operations as: ${RUN_USER}:${RUN_GROUP}"

# Update, upgrade, and install packages

sudo apt-get update
sudo DEBIAN_FRONTEND=noninteractive apt-get upgrade -y
sudo apt-get install -y apache2 git certbot python3-certbot-apache

# Start and check Apache
sudo apt-get update
sudo DEBIAN_FRONTEND=noninteractive apt-get upgrade -y
sudo apt-get install -y apache2 git certbot python3-certbot-apache

# Start and check Apache

sudo systemctl enable apache2
sudo systemctl start apache2
sudo systemctl --no-pager --full status apache2

if ! sudo systemctl is-active --quiet apache2; then
    echo "ERROR: apache2 is not running." >&2
    exit 1
fi

# Prepare the website directory
sudo chown -R "${RUN_USER}:${RUN_GROUP}" "${WEB_ROOT}"

# The default Ubuntu Apache installation creates /var/www/html as a symlink.
# Remove it only when it is actually a symbolic link.
if [[ -L "${HTML_LINK}" ]]; then
    sudo rm "${HTML_LINK}"
elif [[ -e "${HTML_LINK}" ]]; then
    echo "ERROR: ${HTML_LINK} exists but is not a symbolic link; it was not removed." >&2
    exit 1
fi
# Clone Lab 2B and create the html link
if [[ -e "${REPO_PATH}" ]]; then
    echo "ERROR: ${REPO_PATH} already exists; refusing to overwrite it." >&2
    exit 1
fi

sudo -u "${RUN_USER}" git clone "${GITHUB_REPO_URL}" "${REPO_PATH}"
sudo chown -R "${RUN_USER}:${RUN_GROUP}" "${REPO_PATH}"
sudo ln -s "${REPO_PATH}" "${HTML_LINK}"

# Configure and enable the Apache site

cd "${SITE_DIR}"
sudo cp 000-default.conf "${SITE_NAME}"

# Configure the copied site for this domain and the /var/www/html symlink.
if sudo grep -qE '^[[:space:]]*ServerName[[:space:]]+' "${SITE_DIR}/${SITE_NAME}"; then
    sudo sed -i -E "s|^[[:space:]]*ServerName[[:space:]]+.*|    ServerName ${DOMAIN}|" "${SITE_DIR}/${SITE_NAME}"
else
    sudo sed -i "/^[[:space:]]*ServerAdmin[[:space:]]/a\\    ServerName ${DOMAIN}" "${SITE_DIR}/${SITE_NAME}"
fi
sudo sed -i -E "s|^[[:space:]]*DocumentRoot[[:space:]]+.*|    DocumentRoot ${HTML_LINK}|" "${SITE_DIR}/${SITE_NAME}"

sudo a2dissite 000-default.conf
sudo a2ensite "${SITE_NAME}"
sudo apache2ctl configtest
sudo systemctl reload apache2

# Step 2: obtain and test the TLS cert
sudo certbot --apache \
    --non-interactive \
    --agree-tos \
    --keep-until-expiring \
    --redirect \
    --email "${CERTBOT_EMAIL}" \
    --domain "${DOMAIN}"

# Confirm that automatic renewal works.
sudo certbot renew --dry-run

sudo apache2ctl configtest
sudo systemctl reload apache2

echo
echo "Setup complete. Test: https://${DOMAIN}"