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

cd /root

echo "=== precheck date ==="
date

echo "=== greatdb/mysql port precheck ==="
ps -ef | grep -E 'greatdbd|mysqld|mariadbd' | grep -v grep || true
ss -lntp 2>/dev/null | grep -E ':(3306)\b' || true

echo "=== fix soft.lnmp.com hosts only ==="
ts="$(date +%F-%H%M%S)"
cp /etc/hosts "/etc/hosts.bak.lnmp-cdn-${ts}"
sed -i '/soft\.lnmp\.com/d' /etc/hosts
printf '%s\n' '43.174.102.51 soft.lnmp.com' >> /etc/hosts
grep soft.lnmp.com /etc/hosts

echo "=== verify lnmp package ==="
test -s /root/lnmp2.2.tar.gz
tar -tzf /root/lnmp2.2.tar.gz >/dev/null

echo "=== archive old logs ==="
mv /root/lnmp-install-run.log "/root/lnmp-install-run.before-${ts}.log" 2>/dev/null || true
mv /root/lnmp-install.log "/root/lnmp-install.before-${ts}.log" 2>/dev/null || true

echo "=== reset source directory ==="
rm -rf /root/lnmp2.2
tar zxf /root/lnmp2.2.tar.gz
cd /root/lnmp2.2
sed -i "s#^Download_Mirror=.*#Download_Mirror='https://soft.lnmp.com'#" lnmp.conf
grep -n '^Download_Mirror' lnmp.conf

echo "=== start lnmp install: DBSelect=0 means no MySQL/MariaDB ==="
nohup env DBSelect=0 PHPSelect=9 SelectMalloc=1 LNMP_Auto=y CheckMirror=n ./install.sh lnmp > /root/lnmp-install-run.log 2>&1 &
echo "$!" > /root/lnmp-install-run.pid
echo "LNMP install pid=$(cat /root/lnmp-install-run.pid)"

echo "=== post-start process ==="
ps -ef | grep -E 'install.sh|yum|dnf|make|configure|wget' | grep -v grep || true
