#!/bin/bash
# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2026 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT

# RPM post script, no arguments
# Note: Also called from Debian ea-apache24-mod_lsapi.postinst scriptlet

# "ea-apache24-mod_lsapi POST INSTALL STARTED"

rhel=$2
_httpd_conf_dir=$3
_httpd_mod_dir=$4

# CL: /etc/apache2/conf.d
# Ubuntu: /etc/apache2/conf-available

if [[ $rhel -lt 7 ]]; then
  /sbin/chkconfig --add lsapi-cache
else
  systemctl enable lsapi-cache.service >/dev/null 2>&1
fi

if [ -e "${_httpd_conf_dir}"/lsapi.conf.rpmorig ]; then
    mv -f "${_httpd_conf_dir}"/lsapi.conf.rpmorig "${_httpd_conf_dir}"/lsapi.conf
fi

if [ -e "${_httpd_conf_dir}"/lsapi.conf ]; then
    sed -i '/AddHandler/d' "/etc/apache2/conf.d/lsapi.conf"
    sed -i '/FilesMatch/d' "/etc/apache2/conf.d/lsapi.conf"
fi

if [ -e "${_httpd_conf_dir}"/lsapi.conf ]; then
    chmod 644 "${_httpd_conf_dir}"/lsapi.conf
fi

if [ -e "${_httpd_mod_dir}"/001_mod_lsapi.conf ]; then
    chmod 644 "${_httpd_mod_dir}"/001_mod_lsapi.conf
fi


switch_mod_lsapi --setup-light

if [[ "$1" == 1 || "$1" == "install" ]]; then
    switch_mod_lsapi --setup
fi

# Upgrade-path remediation for F-01: pre-existing per-tenant and common
# lsphp stderr logs that were created on disk by a pre-fix mod_lsapi keep
# their old 0644 mode forever — the open() that sets the mode runs once at
# O_CREAT|O_EXCL time, the EEXIST fallback at sulsphp.c:1013 does not
# fchmod, and logrotate copytruncate (sulsphp_logs.EA3/EA4) preserves the
# original inode and mode. Tighten the existing files now so the upgraded
# host actually has the 0600 property the C-side fix promises. Silent on
# missing directories — only the panel/distro-relevant paths exist on a
# given host.
for d in /var/log/httpd /var/log/httpd${httpd24_additional_folder_name:-} \
         /var/log/apache2 /usr/local/apache/logs; do
    [ -d "$d" ] || continue
    find "$d" -maxdepth 1 -type f -name 'lsphp-*stderr.log' -exec chmod 0600 {} + 2>/dev/null || true
done

# "ea-apache24-mod_lsapi POST INSTALL FINISHED"
