#!/bin/bash

# OpenResty Installer Script for Ubuntu 22.04 and above
# Author: najahi@zephyrus.id
# Version: 1.0

if [ "$(id -u)" -ne 0 ]; then
    echo "This script must be run as root. Use sudo ./install_openresty.sh"
    exit 1
fi

echo "Updating package list..."
apt-get update -y > /dev/null

echo "Installing prerequisites..."
apt-get install -y wget gnupg2 software-properties-common lsb-release > /dev/null

echo "Adding OpenResty GPG key..."
wget -qO - https://openresty.org/package/pubkey.gpg | gpg --dearmor | tee /usr/share/keyrings/openresty-archive-keyring.gpg > /dev/null

echo "Adding OpenResty repository..."
echo "deb [signed-by=/usr/share/keyrings/openresty-archive-keyring.gpg] http://openresty.org/package/ubuntu $(lsb_release -sc) main" \
    | tee /etc/apt/sources.list.d/openresty.list > /dev/null

echo "Updating package list after adding OpenResty repository..."
apt-get update -y > /dev/null

echo "Installing OpenResty..."
apt-get install -y openresty > /dev/null

if command -v openresty &> /dev/null; then
    echo "OpenResty installed successfully!"
    echo "Version: $(openresty -v)"
else
    echo "OpenResty installation failed."
    exit 1
fi

echo "Enabling and starting OpenResty service..."
systemctl enable openresty
systemctl start openresty

echo "Checking OpenResty service status..."
systemctl status openresty --no-pager

echo "OpenResty installation complete!"
echo "You can now configure OpenResty at /usr/local/openresty/nginx/conf/nginx.conf"
