#!/usr/bin/env bash
set -Eeuo pipefail
umask 077
cd -- "$(dirname -- "${BASH_SOURCE[0]}")"
BASE=$PWD
WEB=/home/meachou/suporte.meachou.com.br
PRIVATE=/home/meachou/.meachou-suporte
DATA=/var/lib/meachou-suporte
BIN=/opt/meachou-suporte
PHP=/usr/local/bin/php
[[ $EUID == 0 ]] || { echo 'Execute como root.'; exit 1; }
[[ -x $PHP ]] || PHP=$(command -v php)
for c in curl unzip sha256sum systemctl ss runuser install getent useradd; do command -v "$c" >/dev/null || { echo "Falta: $c"; exit 1; }; done
id meachou >/dev/null
[[ -d $WEB && ! -L $WEB ]] || { echo "Crie o subdomínio no cPanel primeiro: $WEB"; exit 1; }
[[ ! -L $PRIVATE && ! -L $DATA && ! -L $BIN ]] || { echo 'Diretório inesperado (link simbólico).'; exit 1; }
"$PHP" -r 'if(PHP_VERSION_ID<70400 || !extension_loaded("pdo_mysql")) {fwrite(STDERR,"PHP 7.4+ e pdo_mysql necessários.\n");exit(1);}'
for path in index.php admin/index.php app.php style.css ui.js; do
  if [[ -e "$WEB/$path" && ! -f "$PRIVATE/installed" ]]; then echo "Arquivo existente: $WEB/$path. Preserve/mova antes de instalar."; exit 1; fi
  [[ ! -L "$WEB/$path" ]] || exit 1
done
[[ ! -L "$WEB/admin" ]] || exit 1
if [[ ! -f "$BIN/managed" ]]; then
  [[ ! -e "$BIN" && ! -e "$DATA" ]] || { echo 'Diretórios de motor já existem; verifique antes de prosseguir.'; exit 1; }
  for u in meachou-suporte-hbbs meachou-suporte-hbbr; do [[ ! -e /etc/systemd/system/$u.service ]] || { echo "Serviço existente: $u"; exit 1; }; done
  if ss -H -lntu | awk '{print $5}' | grep -Eq ':(21115|21116|21117|21118|21119)$'; then echo 'Portas RustDesk já ocupadas. Não alterei os serviços existentes.'; exit 1; fi
fi
install -d -m 0700 -o meachou -g meachou "$PRIVATE"
# Prepare database and admin before downloading or starting services.
SETUP=$(mktemp /tmp/meachou-suporte-install.XXXXXX.php)
trap 'rm -f -- "$SETUP"' EXIT
install -m 0600 -o meachou -g meachou "$BASE/instalar.php" "$SETUP"
runuser -u meachou -- "$PHP" "$SETUP" "$PRIVATE" </dev/tty
rm -f -- "$SETUP"
case $(uname -m) in
 x86_64) asset=rustdesk-server-linux-amd64.zip; sum=0565c41affe6c3f409b0bddfaf5a24ccbf3f64f5f8e3fec250b69a0d5f6bdbcf;;
 aarch64) asset=rustdesk-server-linux-arm64v8.zip; sum=6a4ae3c5ca257a4278ded72fd17eb2ca4eeb0356a5425e63a3e7fcb0ec6c155c;;
 *) echo 'Arquitetura não suportada.'; exit 1;;
esac
TMP=$(mktemp -d); trap 'rm -rf -- "$TMP"' EXIT
if [[ ! -f "$BIN/managed" ]]; then
 curl --fail --location --silent --show-error --retry 2 --proto '=https' --max-time 180 "https://github.com/rustdesk/rustdesk-server/releases/download/1.1.16/$asset" -o "$TMP/server.zip"
 echo "$sum  $TMP/server.zip" | sha256sum -c -
 unzip -q "$TMP/server.zip" -d "$TMP/unpacked"
 for b in hbbs hbbr; do f=$(find "$TMP/unpacked" -type f -name "$b" -print -quit); [[ -n $f ]] || exit 1; done
 getent passwd meachou-rd >/dev/null || useradd --system --no-create-home --shell /sbin/nologin meachou-rd
 install -d -m 0755 "$BIN"
 install -d -m 0700 -o meachou-rd -g "$(id -gn meachou-rd)" "$DATA"
 for b in hbbs hbbr; do install -m 0755 "$(find "$TMP/unpacked" -type f -name "$b" -print -quit)" "$BIN/$b"; done
 touch "$BIN/managed"
fi
for b in hbbs hbbr; do
 args='-k _'; [[ $b != hbbs ]] || args='-k _ -r suporte.meachou.com.br:21117'
 cat > "/etc/systemd/system/meachou-suporte-$b.service" <<UNIT
[Unit]
Description=Meachou Suporte $b (RustDesk OSS)
After=network-online.target
Wants=network-online.target
[Service]
User=meachou-rd
WorkingDirectory=$DATA
Environment=HOME=$DATA
ExecStart=$BIN/$b $args
Restart=on-failure
RestartSec=3
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=$DATA
[Install]
WantedBy=multi-user.target
UNIT
 chmod 0644 "/etc/systemd/system/meachou-suporte-$b.service"
done
systemctl daemon-reload
systemctl enable --now meachou-suporte-hbbs
for i in {1..25}; do [[ -s "$DATA/id_ed25519.pub" && -s "$DATA/id_ed25519" ]] && break; sleep 1; done
[[ -s "$DATA/id_ed25519.pub" && -s "$DATA/id_ed25519" ]] || { journalctl -u meachou-suporte-hbbs -n 20 --no-pager; exit 1; }
systemctl enable --now meachou-suporte-hbbr
sleep 2
systemctl is-active --quiet meachou-suporte-hbbs
systemctl is-active --quiet meachou-suporte-hbbr
install -m 0600 -o meachou -g meachou "$DATA/id_ed25519.pub" "$PRIVATE/server.pub"
install -d -m 0755 -o meachou -g meachou "$WEB/admin"
# Preserve any unrelated files, do not recursively change ownership.
for path in index.php admin/index.php app.php style.css ui.js; do install -m 0644 -o meachou -g meachou "$BASE/site/$path" "$WEB/$path"; done
install -m 0600 -o meachou -g meachou /dev/null "$PRIVATE/installed"
echo 'Instalação local concluída. Confira SSL/DNS e portas no firewall antes do teste externo.'
echo 'Site: https://suporte.meachou.com.br/ | Admin: https://suporte.meachou.com.br/admin/'
echo 'TCP 21115,21116,21117; UDP 21116. Mantenha TCP 21118,21119 fechadas.'
