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

# Usage: scripts/install-vhost.sh [repo-path]
# If repo-path is omitted, the script will use the repository root (parent of scripts/).

TEMPLATE="$(dirname "$0")/../apache/docs-localhost.conf.template"
DEST="/etc/apache2/sites-available/docs-localhost.conf"

if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then
  cat <<EOF
Usage: $0 [repo-path]

Installs and enables an Apache vhost for this repo using the template in apache/docs-localhost.conf.template.
If repo-path is omitted the script will use the repository root (parent of scripts/).
You must run this script on a machine with Apache (a2enmod/a2ensite) and sudo privileges.
EOF
  exit 0
fi

REPO_PATH="${1:-$(cd "$(dirname "$0")/.." && pwd)}"

if [[ "${REPO_PATH}" == -* ]]; then
  echo "Error: the provided repo-path looks like a flag: ${REPO_PATH}." >&2
  echo "Use -h/--help for usage." >&2
  exit 1
fi

if [ ! -d "${REPO_PATH}" ]; then
  echo "Error: repository path '${REPO_PATH}' does not exist or is not a directory." >&2
  exit 1
fi

if [ ! -d "${REPO_PATH}/public" ]; then
  echo "Error: DocumentRoot '${REPO_PATH}/public' does not exist; make sure this is the root of a Laravel project." >&2
  exit 1
fi

if [ ! -f "$TEMPLATE" ]; then
  echo "Template not found: $TEMPLATE"
  exit 1
fi

# Copy and replace placeholder
sudocp_msg='About to copy and update vhost template to: '
echo "Installing vhost to $DEST with REPO_PATH=${REPO_PATH}"
sudo cp "$TEMPLATE" "$DEST"
sudo sed -i "s|{{REPO_PATH}}|${REPO_PATH}|g" "$DEST"

# Ensure rewrite is enabled
sudo a2enmod rewrite || true

# Enable the vhost (ignore if already enabled)
sudo a2ensite docs-localhost.conf || true

# Reload Apache to apply the changes
sudo systemctl reload apache2

cat <<EOF
VHost installed to $DEST with DocumentRoot ${REPO_PATH}/public
Make sure you have an entry in /etc/hosts: 127.0.0.1 docs.localhost
EOF
