install-eye.sh 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021
  1. #!/bin/bash
  2. # Eye Installation Script for ALT Linux/Debian/Ubuntu with PostgreSQL support
  3. # Version: 1.0
  4. # set -e
  5. # Colors for output
  6. RED='\033[0;31m'
  7. GREEN='\033[0;32m'
  8. YELLOW='\033[1;33m'
  9. BLUE='\033[0;34m'
  10. NC='\033[0m' # No Color
  11. # Output functions
  12. print_info() {
  13. echo -e "${GREEN}[INFO]${NC} $1"
  14. }
  15. print_warn() {
  16. echo -e "${YELLOW}[WARN]${NC} $1"
  17. }
  18. print_error() {
  19. echo -e "${RED}[ERROR]${NC} $1"
  20. }
  21. print_step() {
  22. echo -e "${BLUE}=== $1 ===${NC}"
  23. }
  24. # Check for root privileges
  25. check_root() {
  26. if [[ $EUID -ne 0 ]]; then
  27. print_error "This script must be run as root"
  28. print_error "Use: sudo $0"
  29. exit 1
  30. fi
  31. }
  32. service_exists() {
  33. systemctl cat "$1.service" >/dev/null 2>&1
  34. }
  35. safe_start_service() {
  36. local svc="$1"
  37. if service_exists "$svc"; then
  38. if systemctl start "$svc"; then
  39. print_info "Service ${svc} has been successfully started"
  40. else
  41. print_error "Failed to start ${svc}"
  42. fi
  43. fi
  44. }
  45. safe_stop_service() {
  46. local svc="$1"
  47. if service_exists "$svc"; then
  48. if systemctl stop "$svc"; then
  49. print_info "Service ${svc} has been successfully stopped"
  50. else
  51. print_error "Failed to stop ${svc}"
  52. fi
  53. fi
  54. }
  55. stop_eye() {
  56. print_step "Stopping services"
  57. local PHP_VERSION
  58. PHP_VERSION=$(php -v 2>/dev/null | head -n1 | grep -oP '\d+\.\d+' || echo "")
  59. if [ -n "${PHP_VERSION}" ]; then
  60. safe_stop_service "php${PHP_VERSION}-fpm"
  61. fi
  62. for svc in cron eye-statd dhcp-log stat-sync syslog-stat; do
  63. safe_stop_service "$svc"
  64. done
  65. }
  66. start_eye() {
  67. print_step "Starting services"
  68. local PHP_VERSION
  69. PHP_VERSION=$(php -v 2>/dev/null | head -n1 | grep -oP '\d+\.\d+' || echo "")
  70. if [ -n "${PHP_VERSION}" ]; then
  71. safe_start_service "php${PHP_VERSION}-fpm"
  72. fi
  73. for svc in cron eye-statd dhcp-log stat-sync syslog-stat; do
  74. safe_start_service "$svc"
  75. done
  76. }
  77. # Detect distribution and package manager
  78. detect_distro() {
  79. if [[ -f /etc/os-release ]]; then
  80. . /etc/os-release
  81. OS_ID=$ID
  82. OS_VERSION=$VERSION_ID
  83. OS_NAME=$NAME
  84. case $OS_ID in
  85. altlinux)
  86. PACKAGE_MANAGER="apt-get"
  87. SERVICE_MANAGER="systemctl"
  88. OS_FAMILY="alt"
  89. print_info "Detected ALT Linux $OS_VERSION"
  90. ;;
  91. debian)
  92. PACKAGE_MANAGER="apt"
  93. SERVICE_MANAGER="systemctl"
  94. OS_FAMILY="debian"
  95. print_info "Detected Debian $OS_VERSION"
  96. ;;
  97. ubuntu)
  98. PACKAGE_MANAGER="apt"
  99. SERVICE_MANAGER="systemctl"
  100. OS_FAMILY="debian"
  101. print_info "Detected Ubuntu $OS_VERSION"
  102. ;;
  103. *)
  104. print_error "Unsupported distribution: $OS_ID"
  105. print_error "Supported: ALT Linux, Debian, Ubuntu"
  106. exit 1
  107. ;;
  108. esac
  109. else
  110. print_error "Failed to detect distribution"
  111. exit 1
  112. fi
  113. }
  114. select_language() {
  115. print_step "Select Installation Language"
  116. echo "Available languages:"
  117. echo "1) English"
  118. echo "2) Russian (default)"
  119. echo ""
  120. while true; do
  121. read -p "Select language (1 or 2) [2]: " lang_choice
  122. # Если пустой ввод - по умолчанию английский
  123. if [[ -z "$lang_choice" ]]; then
  124. lang_choice="2"
  125. fi
  126. # Обработка ввода (приводим к нижнему регистру)
  127. lang_choice_lower=$(echo "$lang_choice" | tr '[:upper:]' '[:lower:]')
  128. case $lang_choice_lower in
  129. 1|english|en|eng|анг|английский)
  130. EYE_LANG="english"
  131. EYE_LANG_SHORT="en"
  132. print_info "Selected English language"
  133. break
  134. ;;
  135. 2|russian|ru|rus|ру|русский)
  136. EYE_LANG="russian"
  137. EYE_LANG_SHORT="ru"
  138. print_info "Selected Russian language (Русский)"
  139. break
  140. ;;
  141. *)
  142. print_error "Invalid choice: '$lang_choice'"
  143. print_warn "Available options: 1 (English), 2 (Russian)"
  144. print_warn "You can also type: english, en, russian, ru"
  145. ;;
  146. esac
  147. done
  148. }
  149. # Ask user for database type
  150. select_database_type() {
  151. print_step "Select Database Type"
  152. echo "Available database types:"
  153. echo "1) MySQL/MariaDB (default)"
  154. echo "2) PostgreSQL"
  155. echo ""
  156. read -p "Select database type (1 or 2) [1]: " db_choice
  157. case $db_choice in
  158. 2|postgres|postgresql|pgsql)
  159. DB_TYPE="postgresql"
  160. print_info "Selected PostgreSQL"
  161. ;;
  162. *)
  163. DB_TYPE="mysql"
  164. print_info "Selected MySQL/MariaDB"
  165. ;;
  166. esac
  167. }
  168. # Настройка параметров подключения к БД (общая для local и remote)
  169. configure_database_connection() {
  170. echo ""
  171. if [[ "$DB_INSTALL" == "local" ]]; then
  172. echo "Local Database Configuration"
  173. echo "============================"
  174. DB_HOST="127.0.0.1"
  175. if [[ "$DB_TYPE" == "postgresql" ]]; then
  176. DB_PORT="5432"
  177. else
  178. DB_PORT="3306"
  179. fi
  180. echo "Database server: $DB_HOST:$DB_PORT (local)"
  181. else
  182. echo "Remote Database Configuration"
  183. echo "============================"
  184. read -p "Database server IP address: " DB_HOST
  185. read -p "Database port [$([ "$DB_TYPE" == "postgresql" ] && echo "5432" || echo "3306")]: " DB_PORT
  186. # Установка порта по умолчанию, если не введён
  187. if [[ -z "$DB_PORT" ]]; then
  188. if [[ "$DB_TYPE" == "postgresql" ]]; then
  189. DB_PORT="5432"
  190. else
  191. DB_PORT="3306"
  192. fi
  193. fi
  194. fi
  195. read -p "Database name [stat]: " DB_NAME
  196. read -p "Database username [stat]: " DB_USER
  197. echo ""
  198. # Установка значений по умолчанию
  199. : "${DB_NAME:=stat}"
  200. : "${DB_USER:=stat}"
  201. }
  202. # Function for installation type selection
  203. select_installation_type() {
  204. echo "Select installation type:"
  205. echo "1. Web interface + network backend"
  206. echo "2. Web interface only"
  207. echo "3. Network backend only"
  208. echo ""
  209. read -p "Enter selection number [1]: " install_type
  210. case $install_type in
  211. 1)
  212. INSTALL_TYPE="full"
  213. echo "Selected: Web interface + network backend"
  214. read -p "Install database locally? (y/n) [y]: " install_db
  215. if [[ -z "$install_db" || "$install_db" =~ ^[Yy]$ ]]; then
  216. DB_INSTALL="local"
  217. echo "Local database will be installed"
  218. select_database_type
  219. else
  220. DB_INSTALL="remote"
  221. echo "Remote database configuration"
  222. select_database_type
  223. fi
  224. configure_database_connection
  225. ;;
  226. 2)
  227. INSTALL_TYPE="web"
  228. echo "Selected: Web interface only"
  229. DB_INSTALL="remote"
  230. select_database_type
  231. configure_database_connection
  232. ;;
  233. 3)
  234. INSTALL_TYPE="backend"
  235. echo "Selected: Network backend only"
  236. DB_INSTALL="remote"
  237. select_database_type
  238. configure_database_connection
  239. ;;
  240. *)
  241. INSTALL_TYPE="full"
  242. echo "Default selected: Web interface + network backend"
  243. DB_INSTALL="local"
  244. echo "Local database will be installed"
  245. select_database_type
  246. configure_database_connection
  247. ;;
  248. esac
  249. # Защита от неопределённых переменных
  250. : "${DB_TYPE:=mysql}"
  251. : "${DB_INSTALL:=local}"
  252. : "${DB_HOST:=127.0.0.1}"
  253. : "${DB_NAME:=stat}"
  254. : "${DB_USER:=stat}"
  255. }
  256. # Install dependencies for ALT Linux
  257. install_deps_altlinux() {
  258. print_step "Installing dependencies for ALT Linux"
  259. apt-get update
  260. # Общие утилиты (всегда нужны)
  261. apt-get install -y git wget rsync xxd hwdata pwgen
  262. # === Локальная база данных (если выбрана) ===
  263. if [[ "$DB_INSTALL" == "local" ]]; then
  264. if [[ "$DB_TYPE" == "postgresql" ]]; then
  265. apt-get install -y postgresql17 postgresql17-server postgresql17-contrib postgresql17-perl
  266. else
  267. apt-get install -y mariadb-server mariadb-client
  268. fi
  269. fi
  270. # === Веб-интерфейс (если нужен) ===
  271. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "web" ]]; then
  272. apt-get install -y apache2 php8.2 php8.2-fpm-fcgi apache2-mod_fcgid \
  273. php8.2-intl php8.2-mbstring php8.2-snmp php8.2-zip pear-Mail
  274. if [[ "$DB_TYPE" == "postgresql" ]]; then
  275. apt-get install -y php8.2-pgsql php8.2-pdo_pgsql
  276. else
  277. apt-get install -y php8.2-mysqlnd php8.2-pdo_mysql php8.2-mysqlnd-mysqli
  278. fi
  279. fi
  280. # === Сетевой бэкенд (если нужен) ===
  281. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
  282. apt-get install -y fping iptables ipset
  283. # Общие Perl-модули (независимо от СУБД)
  284. apt-get install -y perl \
  285. perl-Net-Patricia perl-NetAddr-IP perl-Config-Tiny \
  286. perl-Net-DNS perl-DateTime perl-Net-Ping \
  287. perl-Net-Netmask perl-Text-Iconv perl-Net-SNMP \
  288. perl-Net-Telnet perl-DBI \
  289. perl-Parallel-ForkManager perl-Proc-Daemon \
  290. perl-DateTime-Format-DateParse perl-DateTime-Format-Strptime \
  291. perl-Net-OpenSSH perl-File-Tail perl-Tie-File \
  292. perl-Crypt-Rijndael perl-Crypt-CBC perl-CryptX perl-Crypt-DES \
  293. perl-File-Path-Tiny perl-Expect perl-Proc-ProcessTable \
  294. perl-Text-CSV \
  295. perl-DBD-Pg perl-DBD-mysql
  296. fi
  297. # Дополнительные проверки (например, fping — нужны только бэкенду)
  298. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
  299. control fping public
  300. fi
  301. control ping public_caps
  302. }
  303. # Install dependencies for Debian/Ubuntu
  304. install_deps_debian() {
  305. print_step "Installing dependencies for Debian/Ubuntu"
  306. apt-get update
  307. # Общие утилиты (всегда нужны)
  308. apt-get install -y git wget rsync xxd hwdata pwgen bsdmainutils
  309. # === Локальная база данных (если выбрана) ===
  310. if [[ "$DB_INSTALL" == "local" ]]; then
  311. if [[ "$DB_TYPE" == "postgresql" ]]; then
  312. # Устанавливаем generic-пакеты PostgreSQL
  313. apt-get install -y postgresql postgresql-contrib postgresql-server-dev-all
  314. else
  315. apt-get install -y mariadb-server mariadb-client
  316. fi
  317. fi
  318. # === Веб-интерфейс (если нужен) ===
  319. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "web" ]]; then
  320. apt-get install -y apache2 libapache2-mod-fcgid \
  321. php php-fpm \
  322. php-bcmath php-intl php-mbstring php-snmp php-zip php-mail \
  323. php-date php-db
  324. if [[ "$DB_TYPE" == "postgresql" ]]; then
  325. apt-get install -y php-pgsql
  326. else
  327. apt-get install -y php-mysql
  328. fi
  329. fi
  330. # === Сетевой бэкенд (если нужен) ===
  331. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
  332. apt-get install -y fping ipset netfilter-persistent
  333. # Perl и обязательные модули (имена корректны для Ubuntu 24.04)
  334. apt-get install -y perl \
  335. libnet-patricia-perl libnetaddr-ip-perl libconfig-tiny-perl \
  336. libnet-dns-perl libdatetime-perl libnet-netmask-perl \
  337. libtext-iconv-perl libnet-snmp-perl libnet-telnet-perl \
  338. libdbi-perl libparallel-forkmanager-perl libproc-daemon-perl \
  339. libdatetime-format-dateparse-perl libnetwork-ipv4addr-perl \
  340. libnet-openssh-perl libfile-tail-perl libdatetime-format-strptime-perl \
  341. libcrypt-rijndael-perl libcrypt-cbc-perl libcryptx-perl \
  342. libcrypt-des-perl libfile-path-tiny-perl libexpect-perl \
  343. libtext-csv-perl \
  344. libdbd-pg-perl libdbd-mysql-perl
  345. fi
  346. # === Дополнительно (если нужно) ===
  347. # apt-get install -y bind9 bind9-utils bind9-host
  348. }
  349. # System update
  350. update_system() {
  351. print_step "Updating apt cache"
  352. $PACKAGE_MANAGER update -y
  353. }
  354. upgrade_system() {
  355. print_step "Updating system"
  356. if [[ "$PACKAGE_MANAGER" == "apt-get" ]]; then
  357. apt-get dist-upgrade -y
  358. else
  359. $PACKAGE_MANAGER upgrade -y
  360. fi
  361. }
  362. # Install packages
  363. install_packages() {
  364. print_step "Installing packages"
  365. case $OS_FAMILY in
  366. alt)
  367. install_deps_altlinux
  368. ;;
  369. debian)
  370. install_deps_debian
  371. ;;
  372. esac
  373. }
  374. # Create user and group
  375. create_user_group() {
  376. print_step "Creating user and group"
  377. # Create group
  378. if ! getent group eye >/dev/null; then
  379. groupadd --system eye
  380. print_info "Group 'eye' created"
  381. else
  382. print_info "Group 'eye' already exists"
  383. fi
  384. # Create user
  385. if ! id -u eye >/dev/null 2>&1; then
  386. if [[ "$OS_FAMILY" == "alt" ]]; then
  387. # For ALT Linux
  388. useradd --system --shell /bin/bash --home-dir /opt/Eye \
  389. --gid eye --groups eye eye
  390. else
  391. # For Debian/Ubuntu
  392. adduser --system --disabled-password --disabled-login \
  393. --ingroup eye --home=/opt/Eye eye
  394. fi
  395. print_info "User 'eye' created"
  396. else
  397. print_info "User 'eye' already exists"
  398. fi
  399. # Create directory
  400. mkdir -p /opt/Eye
  401. chown eye:eye /opt/Eye
  402. chmod 770 /opt/Eye
  403. # Add nagios to eye group (if exists)
  404. if id -u nagios >/dev/null 2>&1; then
  405. usermod -a -G eye nagios
  406. print_info "User 'nagios' added to group 'eye'"
  407. fi
  408. }
  409. # Check and apply SNMP SHA512 patch
  410. apply_snmp_patch() {
  411. print_info "Checking for SNMPv3 SHA512 support..."
  412. # File paths
  413. USM_PATCH_FILE="/opt/Eye/docs/patches/sha512.patch"
  414. if [[ "$OS_FAMILY" == "alt" ]]; then
  415. USM_PATCH_FILE="/opt/Eye/docs/patches/sha512.alt.patch"
  416. fi
  417. USM_PM_FILE=""
  418. # Search for USM.pm in system
  419. local usm_paths=(
  420. "/usr/share/perl5/Net/SNMP/Security/USM.pm"
  421. "/usr/lib/perl5/vendor_perl/Net/SNMP/Security/USM.pm"
  422. "/usr/local/share/perl5/Net/SNMP/Security/USM.pm"
  423. )
  424. for path in "${usm_paths[@]}"; do
  425. if [[ -f "$path" ]]; then
  426. USM_PM_FILE="$path"
  427. print_info "Found USM.pm: $USM_PM_FILE"
  428. break
  429. fi
  430. done
  431. if [[ -z "$USM_PM_FILE" ]]; then
  432. print_warn "USM.pm file not found in system"
  433. return 1
  434. fi
  435. # Check if patch already applied
  436. if grep -q "AUTH_PROTOCOL_HMACSHA512" "$USM_PM_FILE"; then
  437. print_info "SHA512 patch already applied"
  438. return 0
  439. fi
  440. # Create backup
  441. cp "$USM_PM_FILE" "${USM_PM_FILE}.backup"
  442. print_info "Backup created: ${USM_PM_FILE}.backup"
  443. # Try to apply patch file
  444. local patch_applied=false
  445. if [[ -f "$USM_PATCH_FILE" ]]; then
  446. print_info "Attempting to apply patch from $USM_PATCH_FILE"
  447. # Check if patch can be applied
  448. if patch --dry-run -l -p1 -i "$USM_PATCH_FILE" -r /tmp/patch.rej "$USM_PM_FILE" 2>/dev/null; then
  449. # Apply patch
  450. if patch -l -p1 -i "$USM_PATCH_FILE" "$USM_PM_FILE" 2>/dev/null; then
  451. print_info "Patch successfully applied!"
  452. patch_applied=true
  453. else
  454. print_warn "Failed to apply patch (dry-run passed but actual application failed)"
  455. fi
  456. else
  457. print_warn "Patch cannot be applied automatically (version mismatch)"
  458. # Check differences
  459. print_info "Checking patch differences..."
  460. if [[ -f "/opt/Eye/docs/patches/USM.pm" ]]; then
  461. diff -u "$USM_PM_FILE" "/opt/Eye/docs/patches/USM.pm" > /tmp/usm.diff 2>/dev/null || true
  462. if [[ -s /tmp/usm.diff ]]; then
  463. print_warn "Differences found in USM.pm file"
  464. echo "Differences:"
  465. head -20 /tmp/usm.diff
  466. echo "..."
  467. fi
  468. fi
  469. fi
  470. fi
  471. # If patch not applied, ask user
  472. if [[ "$patch_applied" == false ]]; then
  473. echo ""
  474. print_warn "Automatic patch application failed"
  475. print_warn "Modification of USM.pm file required for SNMPv3 with SHA512 support"
  476. echo ""
  477. read -p "Do you need SNMPv3 SHA512 support? (y/n): " -n 1 -r
  478. echo
  479. if [[ $REPLY =~ ^[Yy]$ ]]; then
  480. # Try to replace the entire file
  481. if [[ -f "/opt/Eye/docs/patches/USM.pm" ]]; then
  482. print_info "Replacing USM.pm file entirely..."
  483. # Check version compatibility
  484. local original_ver=$(grep -i "version" "$USM_PM_FILE" | head -1)
  485. local patch_ver=$(grep -i "version" "/opt/Eye/docs/patches/USM.pm" | head -1)
  486. if [[ -n "$original_ver" && -n "$patch_ver" ]]; then
  487. print_info "Original file version: $original_ver"
  488. print_info "Patch version: $patch_ver"
  489. fi
  490. # Create additional backup
  491. cp "$USM_PM_FILE" "${USM_PM_FILE}.backup.$(date +%Y%m%d_%H%M%S)"
  492. # Replace file
  493. cp -f "/opt/Eye/docs/patches/USM.pm" "$USM_PM_FILE"
  494. # Check if replacement successful
  495. if grep -q "SHA-512" "$USM_PM_FILE"; then
  496. print_info "USM.pm file successfully replaced, SHA512 support added"
  497. # Save replacement info
  498. echo "USM.pm file was replaced for SHA512 support" > "${USM_PM_FILE}.replaced"
  499. echo "Original file saved as: ${USM_PM_FILE}.backup" >> "${USM_PM_FILE}.replaced"
  500. echo "Replacement date: $(date)" >> "${USM_PM_FILE}.replaced"
  501. return 0
  502. else
  503. print_error "Failed to add SHA512 support after file replacement"
  504. # Restore from backup
  505. cp "${USM_PM_FILE}.backup" "$USM_PM_FILE"
  506. return 1
  507. fi
  508. else
  509. print_error "Patched USM.pm file not found in /opt/Eye/docs/patches/"
  510. return 1
  511. fi
  512. else
  513. print_info "SNMPv3 SHA512 support disabled"
  514. return 0
  515. fi
  516. fi
  517. return 0
  518. }
  519. # Download and copy source code
  520. install_source_code() {
  521. print_step "Installing Eye source code"
  522. # Создаём корневой каталог
  523. mkdir -p /opt/Eye
  524. chown eye:eye /opt/Eye
  525. chmod 755 /opt/Eye
  526. # === Устанавливаем документацию (всегда) ===
  527. if [ -d "docs" ]; then
  528. print_info "Copying documentation..."
  529. mkdir -p /opt/Eye/docs
  530. cp -R docs/* /opt/Eye/docs/ 2>/dev/null || true
  531. chown -R eye:eye /opt/Eye/docs
  532. fi
  533. # === Устанавливаем веб-интерфейс (если нужен) ===
  534. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "web" ]]; then
  535. print_info "Copying web interface files..."
  536. mkdir -p /opt/Eye/html/cfg /opt/Eye/html/js
  537. if [ -d "html" ]; then
  538. cp -R html/* /opt/Eye/html/ 2>/dev/null || true
  539. fi
  540. download_additional_scripts
  541. chown -R eye:eye /opt/Eye/html
  542. fi
  543. # === Устанавливаем бэкенд (если нужен) ===
  544. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
  545. print_info "Copying backend scripts..."
  546. mkdir -p /opt/Eye/scripts/cfg /opt/Eye/scripts/log
  547. if [ -d "scripts" ]; then
  548. cp -R scripts/* /opt/Eye/scripts/ 2>/dev/null || true
  549. fi
  550. chmod 750 /opt/Eye/scripts
  551. chmod 770 /opt/Eye/scripts/log
  552. chown -R eye:eye /opt/Eye/scripts
  553. if [[ -f "/opt/Eye/docs/systemd/stat-sync.service" ]]; then
  554. cp /opt/Eye/docs/systemd/stat-sync.service /etc/systemd/system/
  555. systemctl enable stat-sync.service
  556. fi
  557. fi
  558. # Применяем патч (только если установлен бэкенд, т.к. касается SNMP в Perl)
  559. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
  560. apply_snmp_patch
  561. fi
  562. }
  563. # Download additional scripts
  564. download_additional_scripts() {
  565. print_step "Downloading additional scripts"
  566. # Create directories
  567. mkdir -p /opt/Eye/html/js/jq
  568. mkdir -p /opt/Eye/html/js/select2
  569. mkdir -p /opt/Eye/html/js/jstree
  570. # Download jQuery
  571. print_info "Downloading jQuery..."
  572. if ! wget -q https://code.jquery.com/jquery-3.7.0.min.js \
  573. -O /opt/Eye/html/js/jq/jquery.min.js; then
  574. print_warn "Failed to download jQuery, trying alternative source..."
  575. wget -q https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js \
  576. -O /opt/Eye/html/js/jq/jquery.min.js || \
  577. print_error "Failed to download jQuery"
  578. fi
  579. # Download Select2
  580. print_info "Downloading Select2..."
  581. if wget -q https://github.com/select2/select2/archive/4.0.12.tar.gz -O 4.0.12.tar.gz; then
  582. tar -xzf 4.0.12.tar.gz -C /opt/Eye/html/js/select2/ \
  583. --strip-components=2 select2-4.0.12/dist 2>/dev/null || \
  584. tar -xzf 4.0.12.tar.gz -C /opt/Eye/html/js/select2/ \
  585. --strip-components=1 select2-4.0.12/dist 2>/dev/null
  586. rm -f 4.0.12.tar.gz
  587. else
  588. print_warn "Failed to download Select2"
  589. fi
  590. # Download jsTree
  591. print_info "Downloading jsTree..."
  592. if wget -q https://github.com/vakata/jstree/archive/3.3.12.tar.gz -O jstree.tar.gz; then
  593. tar -xzf jstree.tar.gz -C /opt/Eye/html/js/
  594. rsync -a /opt/Eye/html/js/jstree-3.3.12/dist/ /opt/Eye/html/js/jstree/
  595. rm -rf /opt/Eye/html/js/jstree-3.3.12
  596. rm -f jstree.tar.gz
  597. else
  598. print_warn "Failed to download jsTree"
  599. fi
  600. # Set permissions
  601. chown -R eye:eye /opt/Eye/html/js
  602. }
  603. # Configure MySQL
  604. setup_mysql() {
  605. print_step "Configuring MySQL"
  606. # Start and enable service
  607. $SERVICE_MANAGER enable mariadb 2>/dev/null || \
  608. $SERVICE_MANAGER enable mysql 2>/dev/null || true
  609. $SERVICE_MANAGER start mariadb 2>/dev/null || \
  610. $SERVICE_MANAGER start mysql 2>/dev/null || true
  611. # Check MySQL access
  612. if ! command -v mysql &> /dev/null; then
  613. print_error "MySQL client not installed"
  614. return 1
  615. fi
  616. MYSQL_OPT="-u root"
  617. # Check access without password
  618. if mysql -u root -e "SELECT 1;" 2>/dev/null; then
  619. print_info "MySQL accessible with empty password"
  620. echo ""
  621. print_warn "IMPORTANT: Need to set root password for MySQL!"
  622. print_warn "After installation run: mysql_secure_installation"
  623. echo ""
  624. else
  625. # Ask for password and create config file
  626. read -p "Enter MySQL root user password: " DB_ROOT_PASSWORD
  627. echo ""
  628. # Create temporary config file
  629. MYSQL_CNF_FILE="/tmp/mysql_root_eye.cnf"
  630. echo "[client]" > "$MYSQL_CNF_FILE"
  631. echo "user=root" >> "$MYSQL_CNF_FILE"
  632. echo "password=$DB_ROOT_PASSWORD" >> "$MYSQL_CNF_FILE"
  633. chmod 600 "$MYSQL_CNF_FILE"
  634. # Check connection
  635. if mysql --defaults-extra-file="$MYSQL_CNF_FILE" -e "SELECT 1;" &>/dev/null; then
  636. print_info "Successfully connected to MySQL"
  637. MYSQL_OPT="--defaults-extra-file=$MYSQL_CNF_FILE"
  638. else
  639. print_error "Incorrect MySQL root password"
  640. rm -f "$MYSQL_CNF_FILE"
  641. return 1
  642. fi
  643. fi
  644. read -p "Create database and user for Eye? (y/n): " -n 1 -r
  645. echo
  646. if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  647. print_warn "Database creation skipped. Create manually:"
  648. print_warn " mysql -u root -p ${DB_NAME}< ${SQL_CREATE_FILE}"
  649. print_warn " mysql -u root -p ${DB_NAME} < ${SQL_DATA_FILE}"
  650. if [[ -f "$MYSQL_CNF_FILE" ]]; then
  651. rm -f "$MYSQL_CNF_FILE"
  652. fi
  653. return 0
  654. fi
  655. # Generate password for db user
  656. DB_PASS=$(pwgen 16 1)
  657. # === Проверка: существует ли база данных? ===
  658. if mysql $MYSQL_OPT -sN -e "SHOW DATABASES;" | grep -q "^${DB_NAME}$"; then
  659. print_error "Database '$DB_NAME' already exists. The script has been stopped."
  660. exit 120
  661. fi
  662. print_info "Create database..."
  663. # Import main SQL file
  664. mysql $MYSQL_OPT <<EOF
  665. CREATE DATABASE IF NOT EXISTS ${DB_NAME} DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
  666. EOF
  667. if [[ $? -ne 0 ]]; then
  668. print_error "Error creating database ${DB_NAME}"
  669. if [[ -f "$MYSQL_CNF_FILE" ]]; then
  670. rm -f "$MYSQL_CNF_FILE"
  671. fi
  672. exit 121
  673. fi
  674. print_info "Importing database structure..."
  675. mysql $MYSQL_OPT ${DB_NAME} < ${SQL_CREATE_FILE}
  676. if [[ $? -ne 0 ]]; then
  677. print_error "Error importing create_db.sql"
  678. if [[ -f "$MYSQL_CNF_FILE" ]]; then
  679. rm -f "$MYSQL_CNF_FILE"
  680. fi
  681. exit 122
  682. fi
  683. print_info "Database structure imported"
  684. # Import data
  685. print_info "Importing initial data..."
  686. mysql $MYSQL_OPT ${DB_NAME} < ${SQL_DATA_FILE}
  687. if [[ $? -ne 0 ]]; then
  688. print_error "Error importing data.sql !!!"
  689. exit 123
  690. else
  691. print_info "Initial data imported"
  692. fi
  693. # Create db user
  694. print_info "Creating user ${DB_USER}.."
  695. mysql $MYSQL_OPT <<EOF
  696. CREATE USER IF NOT EXISTS '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASS';
  697. GRANT ALL PRIVILEGES ON $DB_NAME.* TO '$DB_USER'@'localhost';
  698. FLUSH PRIVILEGES;
  699. EOF
  700. if [[ $? -ne 0 ]]; then
  701. print_error "Error creating user $DB_USER"
  702. if [[ -f "$MYSQL_CNF_FILE" ]]; then
  703. rm -f "$MYSQL_CNF_FILE"
  704. fi
  705. exit 124
  706. fi
  707. print_info "User $DB_USER successfully created"
  708. # Save password information
  709. echo "MySQL $DB_USER user password: $DB_PASS" > /root/eye_mysql_password.txt
  710. chmod 600 /root/eye_mysql_password.txt
  711. print_info "User $DB_USER password: $DB_PASS"
  712. print_warn "Password saved in /root/eye_mysql_password.txt"
  713. # Clean up temporary file if created
  714. if [[ -f "$MYSQL_CNF_FILE" ]]; then
  715. rm -f "$MYSQL_CNF_FILE"
  716. fi
  717. return 0
  718. }
  719. # Configure PostgreSQL
  720. setup_postgresql() {
  721. print_step "Configuring PostgreSQL"
  722. PGDATA="/var/lib/pgsql/data"
  723. # Для ALT Linux
  724. if [[ "$OS_FAMILY" == "alt" ]]; then
  725. echo "root ALL=(ALL:ALL) NOPASSWD: ALL" >/etc/sudoers.d/root
  726. PGDATA="/var/lib/pgsql/data"
  727. if [ -z "$(ls -A $PGDATA 2>/dev/null)" ]; then
  728. /etc/init.d/postgresql initdb
  729. # === ВАЖНО: настраиваем pg_hba.conf для безпарольного доступа ===
  730. local pg_hba_file="$PGDATA/pg_hba.conf"
  731. if [[ -f "$pg_hba_file" ]]; then
  732. # Делаем резервную копию
  733. cp "$pg_hba_file" "${pg_hba_file}.backup"
  734. # Вставляем правило для пользователя 'postgres' в начало файла
  735. # Это разрешит подключение без пароля через Unix-сокет
  736. sed -i '1i\
  737. # Allow local postgres user without password\
  738. local all postgres peer\
  739. ' "$pg_hba_file"
  740. print_info "Configured pg_hba.conf to allow peer authentication for 'postgres'"
  741. fi
  742. fi
  743. # Start and enable service
  744. $SERVICE_MANAGER enable postgresql
  745. $SERVICE_MANAGER restart postgresql
  746. else
  747. # Start and enable service
  748. $SERVICE_MANAGER enable postgresql
  749. $SERVICE_MANAGER start postgresql
  750. fi
  751. # Check PostgreSQL access
  752. if ! command -v psql &> /dev/null; then
  753. print_error "PostgreSQL client not installed"
  754. exit 110
  755. fi
  756. # === Проверка: существует ли БД? ===
  757. if sudo -u postgres psql -lqt | cut -d \| -f 1 | grep -qw "^\s*${DB_NAME}\s*$"; then
  758. print_error "Database '$DB_NAME' already exists. The script has been stopped."
  759. exit 120
  760. fi
  761. # Спросить, создавать ли БД
  762. read -p "Create database and user for Eye? (y/n): " -n 1 -r
  763. echo
  764. if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  765. print_warn "Database creation skipped. Create manually as postgres user:"
  766. print_warn " sudo -u postgres createdb -O $DB_USER $DB_NAME"
  767. print_warn " sudo -u postgres psql -d $DB_NAME -f $SQL_DATA_FILE"
  768. return 0
  769. fi
  770. # Генерация пароля для пользователя БД
  771. if command -v pwgen &> /dev/null; then
  772. DB_PASS=$(pwgen 16 1)
  773. else
  774. DB_PASS=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c16)
  775. fi
  776. # Определяем локаль на основе языка
  777. if [[ "$EYE_LANG" == "russian" ]]; then
  778. LC_TYPE="ru_RU.UTF-8"
  779. else
  780. LC_TYPE="en_US.UTF-8"
  781. fi
  782. print_info "Creating database '$DB_NAME' with locale '$LC_TYPE'..."
  783. # Set password for stat user
  784. print_info "Setting password for user $DB_USER ..."
  785. sudo -u postgres psql -c "CREATE USER $DB_USER WITH PASSWORD '$DB_PASS';"
  786. sudo -u postgres createdb \
  787. --encoding=UTF8 \
  788. --lc-collate="$LC_TYPE" \
  789. --lc-ctype="$LC_TYPE" \
  790. --template=template0 \
  791. --owner="$DB_USER" \
  792. "$DB_NAME"
  793. if [[ $? -ne 0 ]]; then
  794. print_error "Failed to create database"
  795. exit 121
  796. fi
  797. print_info "Database created successfully with owner '$DB_USER'"
  798. sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;"
  799. # Теперь подключаемся как новый владелец для импорта
  800. print_info "Importing database structure as '$DB_USER'..."
  801. # Вариант 1: Используя sudo и переключение пользователя в psql
  802. sudo -u postgres psql -d "$DB_NAME" <<EOF
  803. SET ROLE "$DB_USER";
  804. \i $SQL_CREATE_FILE
  805. EOF
  806. if [[ $? -ne 0 ]]; then
  807. print_error "Error importing create_db.sql"
  808. exit 122
  809. fi
  810. print_info "Database structure imported successfully"
  811. # Импортируем данные тоже как владелец
  812. if [[ -f "$SQL_DATA_FILE" ]]; then
  813. print_info "Importing database data as '$DB_USER'..."
  814. sudo -u postgres psql -d "$DB_NAME" <<EOF
  815. SET ROLE "$DB_USER";
  816. \i $SQL_DATA_FILE
  817. EOF
  818. if [[ $? -ne 0 ]]; then
  819. print_error "Warning: failed to import data (may already exist or non-critical)"
  820. exit 123
  821. else
  822. print_info "Database data imported successfully"
  823. fi
  824. fi
  825. # Дополнительные привилегии
  826. print_info "Setting up additional privileges..."
  827. # Дать доступ пользователю postgres к БД
  828. sudo -u postgres psql -c "GRANT CONNECT ON DATABASE $DB_NAME TO postgres;"
  829. # Дать полные права пользователю postgres на все объекты
  830. sudo -u postgres psql -d "$DB_NAME" <<EOF
  831. GRANT ALL ON SCHEMA public TO postgres;
  832. ALTER DEFAULT PRIVILEGES FOR USER "$DB_USER" IN SCHEMA public GRANT ALL ON TABLES TO postgres;
  833. ALTER DEFAULT PRIVILEGES FOR USER "$DB_USER" IN SCHEMA public GRANT ALL ON SEQUENCES TO postgres;
  834. ALTER DEFAULT PRIVILEGES FOR USER "$DB_USER" IN SCHEMA public GRANT ALL ON FUNCTIONS TO postgres;
  835. EOF
  836. print_info "Database setup completed successfully"
  837. # Configure PostgreSQL for MD5 authentication
  838. if [[ "$OS_FAMILY" == "alt" ]]; then
  839. local pg_hba_file="/var/lib/pgsql/data/pg_hba.conf"
  840. if [[ -f "$pg_hba_file" ]]; then
  841. # Backup original
  842. cp "$pg_hba_file" "${pg_hba_file}.backup"
  843. # Add local md5 authentication if not present
  844. if ! grep -q "local.*$DB_NAME.*md5" "$pg_hba_file"; then
  845. echo "local $DB_NAME $DB_USER scram-sha-256" >> "$pg_hba_file"
  846. print_info "Added MD5 authentication for $DB_USER user in pg_hba.conf"
  847. fi
  848. fi
  849. else
  850. local pg_hba_file="/etc/postgresql/$(ls /etc/postgresql/ | head -1)/main/pg_hba.conf"
  851. if [[ -f "$pg_hba_file" ]]; then
  852. # Backup original
  853. cp "$pg_hba_file" "${pg_hba_file}.backup"
  854. # Add local md5 authentication if not present
  855. if ! grep -q "local.*$DB_NAME.*md5" "$pg_hba_file"; then
  856. echo "local $DB_NAME $DB_USER scram-sha-256" >> "$pg_hba_file"
  857. print_info "Added MD5 authentication for $DB_USER user in pg_hba.conf"
  858. fi
  859. fi
  860. fi
  861. # Restart PostgreSQL to apply changes
  862. $SERVICE_MANAGER restart postgresql
  863. # Save password information
  864. echo "PostgreSQL $DB_USER user password: $DB_PASS" > /root/eye_postgres_password.txt
  865. chmod 600 /root/eye_postgres_password.txt
  866. print_info "User $DB_USER password: $DB_PASS"
  867. print_warn "Password saved in /root/eye_postgres_password.txt"
  868. return 0
  869. }
  870. # Configure database based on selected type
  871. setup_database() {
  872. # Пропускаем настройку, если БД — удалённая
  873. if [[ "$DB_INSTALL" != "local" ]]; then
  874. print_info "Database is configured remotely — skipping local setup"
  875. return 0
  876. fi
  877. print_step "Setting up local database"
  878. # Определяем пути к SQL-файлам в зависимости от типа БД и языка
  879. if [[ "$DB_TYPE" == "mysql" ]]; then
  880. if [[ "$EYE_LANG" == "russian" && -d "/opt/Eye/docs/databases/mysql/ru" ]]; then
  881. SQL_DATA_FILE="/opt/Eye/docs/databases/mysql/ru/data.sql"
  882. SQL_CREATE_FILE="/opt/Eye/docs/databases/mysql/ru/create_db.sql"
  883. else
  884. SQL_DATA_FILE="/opt/Eye/docs/databases/mysql/en/data.sql"
  885. SQL_CREATE_FILE="/opt/Eye/docs/databases/mysql/en/create_db.sql"
  886. fi
  887. elif [[ "$DB_TYPE" == "postgresql" ]]; then
  888. if [[ "$EYE_LANG" == "russian" && -d "/opt/Eye/docs/databases/postgres/ru" ]]; then
  889. SQL_DATA_FILE="/opt/Eye/docs/databases/postgres/ru/data.sql"
  890. SQL_CREATE_FILE="/opt/Eye/docs/databases/postgres/ru/create_db.sql"
  891. else
  892. SQL_DATA_FILE="/opt/Eye/docs/databases/postgres/en/data.sql"
  893. SQL_CREATE_FILE="/opt/Eye/docs/databases/postgres/en/create_db.sql"
  894. fi
  895. else
  896. print_error "Unsupported database type: $DB_TYPE"
  897. exit 130
  898. fi
  899. # Проверка существования файлов
  900. if [[ ! -f "$SQL_CREATE_FILE" || ! -f "$SQL_DATA_FILE" ]]; then
  901. print_error "SQL files not found for DB_TYPE=$DB_TYPE and EYE_LANG=$EYE_LANG"
  902. exit 131
  903. fi
  904. print_info "Using SQL files for $EYE_LANG language"
  905. # Выполняем настройку в зависимости от СУБД
  906. if [[ "$DB_TYPE" == "postgresql" ]]; then
  907. setup_postgresql
  908. else
  909. setup_mysql
  910. fi
  911. }
  912. # Configure configuration files
  913. setup_configs() {
  914. print_step "Configuring configuration files"
  915. # Генерация или запрос ключей шифрования
  916. print_info "Setting up encryption keys..."
  917. if [[ "$DB_INSTALL" == "local" ]]; then
  918. # Для локальной БД — генерируем автоматически
  919. if command -v pwgen &> /dev/null; then
  920. ENC_PASSWORD=$(pwgen 16 1)
  921. else
  922. ENC_PASSWORD=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c16)
  923. fi
  924. ENC_VECTOR=$(tr -dc 0-9 </dev/urandom | head -c 16)
  925. print_info "Encryption keys generated automatically (local database)."
  926. print_info "Password: $ENC_PASSWORD"
  927. print_info "Vector: $ENC_VECTOR"
  928. else
  929. # Для удалённой БД — ОБЯЗАТЕЛЬНО запрашиваем у пользователя
  930. echo ""
  931. print_info "Remote database detected. You MUST provide the encryption keys"
  932. print_info "that are already in use by other Eye components connected to this database."
  933. echo ""
  934. while [[ -z "$ENC_PASSWORD" ]]; do
  935. read -p "Enter ENCRYPTION_KEY (16+ characters): " ENC_PASSWORD
  936. if [[ ${#ENC_PASSWORD} -lt 16 ]]; then
  937. print_warn "Key should be at least 16 characters long."
  938. ENC_PASSWORD=""
  939. fi
  940. done
  941. while [[ -z "$ENC_VECTOR" ]]; do
  942. read -p "Enter ENCRYPTION_IV (exactly 16 digits): " ENC_VECTOR
  943. if [[ ! "$ENC_VECTOR" =~ ^[0-9]{16}$ ]]; then
  944. print_warn "IV must consist of exactly 16 digits (0-9)."
  945. ENC_VECTOR=""
  946. fi
  947. done
  948. print_info "Encryption keys accepted for remote database."
  949. fi
  950. # === Настройка веб-конфигурации (только если нужен веб) ===
  951. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "web" ]]; then
  952. if [[ -f "/opt/Eye/html/cfg/config.sample.php" ]]; then
  953. cp /opt/Eye/html/cfg/config.sample.php /opt/Eye/html/cfg/config.php
  954. # Определяем DB_TYPE для PHP (mysql или pgsql)
  955. PHP_DB_TYPE="$DB_TYPE"
  956. [[ "$DB_TYPE" == "postgresql" ]] && PHP_DB_TYPE="pgsql"
  957. # Подстановка реальных значений
  958. sed -i "s/define(\"DB_TYPE\",\"[^\"]*\");/define(\"DB_TYPE\",\"$PHP_DB_TYPE\");/" /opt/Eye/html/cfg/config.php
  959. sed -i "s/define(\"DB_HOST\",\"[^\"]*\");/define(\"DB_HOST\",\"$DB_HOST\");/" /opt/Eye/html/cfg/config.php
  960. sed -i "s/define(\"DB_PORT\",\"[^\"]*\");/define(\"DB_PORT\",\"$DB_PORT\");/" /opt/Eye/html/cfg/config.php
  961. sed -i "s/define(\"DB_NAME\",\"[^\"]*\");/define(\"DB_NAME\",\"$DB_NAME\");/" /opt/Eye/html/cfg/config.php
  962. sed -i "s/define(\"DB_USER\",\"[^\"]*\");/define(\"DB_USER\",\"$DB_USER\");/" /opt/Eye/html/cfg/config.php
  963. sed -i "s/define(\"DB_PASS\",\"[^\"]*\");/define(\"DB_PASS\",\"$DB_PASS\");/" /opt/Eye/html/cfg/config.php
  964. # Ключи шифрования
  965. sed -i "s/ENCRYPTION_KEY\",\"[^\"]*\"/ENCRYPTION_KEY\",\"$ENC_PASSWORD\"/" /opt/Eye/html/cfg/config.php
  966. sed -i "s/ENCRYPTION_IV\",\"[^\"]*\"/ENCRYPTION_IV\",\"$ENC_VECTOR\"/" /opt/Eye/html/cfg/config.php
  967. print_info "Web configuration file config.php created"
  968. else
  969. print_warn "Web config template not found, skipping PHP config"
  970. fi
  971. fi
  972. # === Настройка конфигурации бэкенда (только если нужен бэкенд) ===
  973. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
  974. if [[ -f "/opt/Eye/scripts/cfg/config.sample" ]]; then
  975. cp /opt/Eye/scripts/cfg/config.sample /opt/Eye/scripts/cfg/config
  976. # Подстановка значений
  977. sed -i "s/^DBTYPE=.*/DBTYPE=$DB_TYPE/" /opt/Eye/scripts/cfg/config
  978. sed -i "s/DBTYPE=db_type/DBTYPE=$DB_TYPE/" /opt/Eye/scripts/cfg/config
  979. sed -i "s/^DBHOST=.*/DBHOST=$DB_HOST/" /opt/Eye/scripts/cfg/config
  980. sed -i "s/^DBPORT=.*/DBPORT=$DB_PORT/" /opt/Eye/scripts/cfg/config
  981. sed -i "s/^DBNAME=.*/DBNAME=$DB_NAME/" /opt/Eye/scripts/cfg/config
  982. sed -i "s/^DBUSER=.*/DBUSER=$DB_USER/" /opt/Eye/scripts/cfg/config
  983. sed -i "s/^DBPASS=.*/DBPASS=$DB_PASS/" /opt/Eye/scripts/cfg/config
  984. # Ключи шифрования
  985. sed -i "s/^encryption_key=.*/encryption_key=$ENC_PASSWORD/" /opt/Eye/scripts/cfg/config
  986. sed -i "s/encryption_key=!!!CHANGE_ME!!!!/encryption_key=$ENC_PASSWORD/" /opt/Eye/scripts/cfg/config
  987. sed -i "s/^encryption_iv=.*/encryption_iv=$ENC_VECTOR/" /opt/Eye/scripts/cfg/config
  988. sed -i "s/encryption_iv=0123456789012345/encryption_iv=$ENC_VECTOR/" /opt/Eye/scripts/cfg/config
  989. print_info "Backend configuration file scripts/cfg/config created"
  990. else
  991. print_warn "Backend config template not found, skipping scripts config"
  992. fi
  993. fi
  994. # === Установка прав (только для существующих каталогов) ===
  995. if [[ -d "/opt/Eye/html/cfg" ]]; then
  996. chown -R eye:eye /opt/Eye/html/cfg
  997. chmod 750 /opt/Eye/html/cfg
  998. chmod 660 /opt/Eye/html/cfg/config.php 2>/dev/null || true
  999. fi
  1000. if [[ -d "/opt/Eye/scripts/cfg" ]]; then
  1001. chown -R eye:eye /opt/Eye/scripts/cfg
  1002. chmod 750 /opt/Eye/scripts/cfg
  1003. chmod 660 /opt/Eye/scripts/cfg/config 2>/dev/null || true
  1004. fi
  1005. }
  1006. # Функция применения языковых настроек к конфигурации
  1007. apply_language_settings() {
  1008. print_info "Applying language settings: $EYE_LANG"
  1009. # Применяем языковые настройки только если установлен веб-интерфейс
  1010. if [[ "$INSTALL_TYPE" != "web" && "$INSTALL_TYPE" != "full" ]]; then
  1011. print_info "Web interface not installed — skipping language configuration"
  1012. return 0
  1013. fi
  1014. # Проверяем, существует ли каталог конфигурации веба
  1015. if [[ ! -d "/opt/Eye/html/cfg" ]]; then
  1016. print_warn "Web config directory not found — skipping language setup"
  1017. return 0
  1018. fi
  1019. CONFIG_PHP="/opt/Eye/html/cfg/config.php"
  1020. if [[ ! -f "$CONFIG_PHP" ]]; then
  1021. print_warn "Web config file not found — skipping language setup"
  1022. return 0
  1023. fi
  1024. if [[ "$EYE_LANG" == "russian" ]]; then
  1025. # Установка русского языка
  1026. sed -i "s/define(\"HTML_LANG\",\"[^\"]*\"\");/define(\"HTML_LANG\",\"russian\");/g" "$CONFIG_PHP"
  1027. sed -i "s/setlocale(LC_ALL, '[^']*');/setlocale(LC_ALL, 'ru_RU.UTF-8');/g" "$CONFIG_PHP"
  1028. print_info "Web interface language set to Russian"
  1029. else
  1030. # Установка английского языка (по умолчанию)
  1031. sed -i "s/define(\"HTML_LANG\",\"[^\"]*\"\");/define(\"HTML_LANG\",\"english\");/g" "$CONFIG_PHP"
  1032. sed -i "s/setlocale(LC_ALL, '[^']*');/setlocale(LC_ALL, 'en_US.UTF-8');/g" "$CONFIG_PHP"
  1033. print_info "Web interface language set to English"
  1034. fi
  1035. }
  1036. # Configure Apache and PHP
  1037. setup_apache_php() {
  1038. print_step "Configuring Apache and PHP"
  1039. # Determine PHP version
  1040. PHP_VERSION=$(php -v 2>/dev/null | head -n1 | grep -oP '\d+\.\d+' || echo "8.2")
  1041. echo "Версия PHP: $PHP_VERSION"
  1042. # Configure PHP for all distributions
  1043. if [[ "$OS_FAMILY" == "alt" ]]; then
  1044. # ALT Linux
  1045. PHP_INI="/etc/php/$PHP_VERSION/apache2/php.ini"
  1046. APACHE_CONF_DIR="/etc/httpd2/conf"
  1047. APACHE_SITES_DIR="$APACHE_CONF_DIR/sites-available"
  1048. DEFAULT_CONF="$APACHE_SITES_DIR/000-default.conf"
  1049. APACHE_USER="apache2"
  1050. else
  1051. # Debian/Ubuntu
  1052. PHP_INI="/etc/php/$PHP_VERSION/apache2/php.ini"
  1053. APACHE_CONF_DIR="/etc/apache2"
  1054. APACHE_SITES_DIR="$APACHE_CONF_DIR/sites-available"
  1055. DEFAULT_CONF="$APACHE_SITES_DIR/000-default.conf"
  1056. APACHE_USER="www-data"
  1057. fi
  1058. # Configure Apache
  1059. if [[ -f "/opt/Eye/docs/apache/000-default.conf" ]]; then
  1060. print_info "Using prepared Apache template for ALT Linux"
  1061. # Create directory if it doesn't exist
  1062. mkdir -p "$APACHE_SITES_DIR"
  1063. # Copy prepared config
  1064. cp "/opt/Eye/docs/apache/000-default.conf" "$DEFAULT_CONF"
  1065. # Enable site
  1066. if [[ -f "$APACHE_CONF_DIR/sites-enabled/000-default.conf" ]]; then
  1067. rm -f "$APACHE_CONF_DIR/sites-enabled/000-default.conf"
  1068. ln -sf "$DEFAULT_CONF" "$APACHE_CONF_DIR/sites-enabled/000-default.conf"
  1069. fi
  1070. fi
  1071. # Configure sudoers
  1072. if [[ -f "/opt/Eye/docs/sudoers.d/www-data" ]]; then
  1073. # Use prepared template, substituting correct user
  1074. sed "s/www-data/eye/g" /opt/Eye/docs/sudoers.d/www-data > /etc/sudoers.d/eye
  1075. chmod 440 /etc/sudoers.d/eye
  1076. print_info "Sudoers file created from template"
  1077. fi
  1078. # Restart Apache
  1079. if [[ "$OS_FAMILY" == "alt" ]]; then
  1080. # ALT Linux uses httpd2
  1081. APACHE_SERVICE="httpd2"
  1082. else
  1083. APACHE_SERVICE="apache2"
  1084. fi
  1085. # usermod -a -G eye $APACHE_USER
  1086. if [[ "$OS_FAMILY" == "debian" ]]; then
  1087. a2dismod php${PHP_VERSION} 2>/dev/null
  1088. a2dismod mpm_prefork 2>/dev/null
  1089. a2enmod mpm_event 2>/dev/null
  1090. a2enconf php${PHP_VERSION}-fpm 2>/dev/null
  1091. fi
  1092. mkdir -p /var/log/php-fpm/
  1093. a2enmod setenvif
  1094. a2enmod proxy
  1095. a2enmod proxy_fcgi
  1096. print_info "Apache configured, sudoers user: $APACHE_USER"
  1097. print_info "Apache service: $APACHE_SERVICE"
  1098. # Configure php-fpm
  1099. print_info "Configure php-fpm${PHP_VERSION}"
  1100. if [[ -f "/opt/Eye/docs/php-fpm/eye.conf" ]]; then
  1101. print_info "Using prepared php-fpm template"
  1102. if [[ "$OS_FAMILY" == "alt" ]]; then
  1103. cp "/opt/Eye/docs/php-fpm/eye.conf" /etc/fpm${PHP_VERSION}/php-fpm.d/
  1104. else
  1105. cp "/opt/Eye/docs/php-fpm/eye.conf" /etc/php/${PHP_VERSION}/fpm/pool.available/
  1106. ln -sf "/etc/php/${PHP_VERSION}/fpm/pool.available/eye.conf" "/etc/php/${PHP_VERSION}/fpm/pool.d/eye.conf"
  1107. fi
  1108. fi
  1109. $SERVICE_MANAGER enable "$APACHE_SERVICE"
  1110. $SERVICE_MANAGER restart "$APACHE_SERVICE"
  1111. $SERVICE_MANAGER enable php${PHP_VERSION}-fpm.service
  1112. $SERVICE_MANAGER restart php${PHP_VERSION}-fpm.service
  1113. # Check configuration
  1114. if [[ "$OS_FAMILY" == "alt" ]]; then
  1115. httpd2 -t 2>/dev/null && print_info "Apache (httpd2) configuration is valid" || print_warn "Check Apache configuration"
  1116. else
  1117. apache2ctl -t 2>/dev/null && print_info "Apache configuration is valid" || print_warn "Check Apache configuration"
  1118. fi
  1119. }
  1120. # Configure cron and logrotate
  1121. setup_cron_logrotate() {
  1122. print_step "Configuring cron and logrotate"
  1123. # Cron
  1124. if [[ -f "/opt/Eye/docs/cron/stat" ]]; then
  1125. cp /opt/Eye/docs/cron/stat /etc/cron.d/eye
  1126. chmod 644 /etc/cron.d/eye
  1127. print_info "Cron job added: /etc/cron.d/eye"
  1128. fi
  1129. # Logrotate
  1130. if [ -f /etc/dnsmasq.conf ] && [ -f "/opt/Eye/docs/logrotate/dnsmasq" ]; then
  1131. cp /opt/Eye/docs/logrotate/dnsmasq /etc/logrotate.d/dnsmasq-eye
  1132. fi
  1133. if [ -e /opt/Eye/scripts ] && [ -f "/opt/Eye/docs/logrotate/scripts" ]; then
  1134. cp /opt/Eye/docs/logrotate/scripts /etc/logrotate.d/eye-scripts
  1135. fi
  1136. print_info "Cron and logrotate configuration completed"
  1137. print_warn "Edit /etc/cron.d/eye to enable required scripts"
  1138. }
  1139. # Configure DHCP server (dnsmasq)
  1140. setup_dhcp_server() {
  1141. print_step "Configuring DHCP server"
  1142. read -p "Configure DHCP server (dnsmasq)? (y/n): " -n 1 -r
  1143. echo
  1144. if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  1145. return 0
  1146. fi
  1147. if [[ "$OS_FAMILY" == "debian" ]]; then
  1148. apt install dnsmasq -y
  1149. else
  1150. apt-get install dnsmasq -y
  1151. fi
  1152. # Backup configuration
  1153. if [[ -f "/etc/dnsmasq.conf" ]]; then
  1154. cp /etc/dnsmasq.conf /etc/dnsmasq.conf.backup
  1155. fi
  1156. # Copy configuration from Eye
  1157. if [[ -f "/opt/Eye/docs/addons/dnsmasq.conf" ]]; then
  1158. cat /opt/Eye/docs/addons/dnsmasq.conf > /etc/dnsmasq.conf
  1159. fi
  1160. # Copy systemd services
  1161. if [[ -f "/opt/Eye/docs/systemd/dhcp-log.service" ]]; then
  1162. cp /opt/Eye/docs/systemd/dhcp-log.service /etc/systemd/system/
  1163. mkdir -p /etc/systemd/system/dnsmasq.service.d
  1164. cp -f /opt/Eye/docs/systemd/dnsmasq.service.d/override.conf /etc/systemd/system/dnsmasq.service.d
  1165. fi
  1166. if [[ -f "/opt/Eye/docs/systemd/dhcp-log-truncate.service" ]]; then
  1167. cp /opt/Eye/docs/systemd/dhcp-log-truncate.service /etc/systemd/system/
  1168. fi
  1169. # Enable services
  1170. $SERVICE_MANAGER enable dnsmasq
  1171. # $SERVICE_MANAGER start dnsmasq
  1172. print_info "DHCP server configured"
  1173. print_warn "Edit /etc/dnsmasq.conf for your network"
  1174. }
  1175. # Configure syslog-ng
  1176. setup_syslog() {
  1177. print_step "Configuring syslog-ng"
  1178. read -p "Configure remote log collection (syslog-ng)? (y/n): " -n 1 -r
  1179. echo
  1180. if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  1181. return 0
  1182. fi
  1183. if [[ "$OS_FAMILY" == "debian" ]]; then
  1184. apt install syslog-ng -y
  1185. else
  1186. apt-get install syslog-ng syslog-ng-journal -y
  1187. fi
  1188. # Create backup of main config
  1189. if [[ -f "/etc/syslog-ng/syslog-ng.conf" ]]; then
  1190. cp /etc/syslog-ng/syslog-ng.conf /etc/syslog-ng/syslog-ng.conf.backup
  1191. print_info "Backup created: /etc/syslog-ng/syslog-ng.conf.backup"
  1192. fi
  1193. # Copy additional config for Eye
  1194. if [[ -f "/opt/Eye/docs/syslog-ng/eye.conf" ]]; then
  1195. mkdir -p /etc/syslog-ng/conf.d
  1196. cp /opt/Eye/docs/syslog-ng/eye.conf /etc/syslog-ng/conf.d/eye.conf
  1197. # Check if conf.d inclusion already exists in main config
  1198. if [[ -f "/etc/syslog-ng/syslog-ng.conf" ]]; then
  1199. if ! grep -q "@include.*conf\.d" /etc/syslog-ng/syslog-ng.conf && \
  1200. ! grep -q "include.*conf\.d" /etc/syslog-ng/syslog-ng.conf; then
  1201. # Add conf.d directory inclusion to end of file
  1202. echo "" >> /etc/syslog-ng/syslog-ng.conf
  1203. echo "# Include Eye monitoring configuration" >> /etc/syslog-ng/syslog-ng.conf
  1204. echo "@include \"/etc/syslog-ng/conf.d/*.conf\"" >> /etc/syslog-ng/syslog-ng.conf
  1205. print_info "Added conf.d directory inclusion to syslog-ng.conf"
  1206. fi
  1207. fi
  1208. print_info "Configuration file eye.conf copied to /etc/syslog-ng/conf.d/"
  1209. else
  1210. print_warn "eye.conf configuration file not found in /opt/Eye/docs/syslog-ng/"
  1211. fi
  1212. # options block
  1213. syslogng_options='options {
  1214. chain_hostnames(off);
  1215. flush_lines(0);
  1216. use_dns(no);
  1217. use_fqdn(no);
  1218. dns_cache(no);
  1219. owner("root");
  1220. group("adm");
  1221. perm(0640);
  1222. stats_freq(0);
  1223. time_reopen(10);
  1224. log_fifo_size(1000);
  1225. create_dirs(yes);
  1226. keep_hostname(no);
  1227. };'
  1228. # Check for options in main config
  1229. if [[ -f "/etc/syslog-ng/syslog-ng.conf" ]]; then
  1230. if ! grep -q "^options\s*{" /etc/syslog-ng/syslog-ng.conf; then
  1231. # Add options block if it doesn't exist
  1232. if grep -q "^@version:" /etc/syslog-ng/syslog-ng.conf; then
  1233. # Insert after @version: line
  1234. sed -i "/^@version:/a\\$syslogng_options" /etc/syslog-ng/syslog-ng.conf
  1235. else
  1236. # Insert at beginning of file
  1237. sed -i "1i\\$syslogng_options" /etc/syslog-ng/syslog-ng.conf
  1238. fi
  1239. print_info "Added options block to syslog-ng.conf"
  1240. else
  1241. # Check for required parameters in existing options block
  1242. local missing_params=()
  1243. if ! grep -q "time_reopen\s*(.*)" /etc/syslog-ng/syslog-ng.conf; then
  1244. missing_params+=("time_reopen(10)")
  1245. fi
  1246. if ! grep -q "log_fifo_size\s*(.*)" /etc/syslog-ng/syslog-ng.conf; then
  1247. missing_params+=("log_fifo_size(1000)")
  1248. fi
  1249. if ! grep -q "chain_hostnames\s*(.*)" /etc/syslog-ng/syslog-ng.conf; then
  1250. missing_params+=("chain_hostnames(off)")
  1251. fi
  1252. if ! grep -q "create_dirs\s*(.*)" /etc/syslog-ng/syslog-ng.conf; then
  1253. missing_params+=("create_dirs(yes)")
  1254. fi
  1255. if ! grep -q "keep_hostname\s*(.*)" /etc/syslog-ng/syslog-ng.conf; then
  1256. missing_params+=("keep_hostname(no)")
  1257. fi
  1258. # Add missing parameters
  1259. if [[ ${#missing_params[@]} -gt 0 ]]; then
  1260. # Find options block and add parameters to end of block
  1261. sed -i '/^options\s*{/,/^}/ {
  1262. /^}/ i\ '"$(IFS='; '; echo "${missing_params[*]}")"';
  1263. }' /etc/syslog-ng/syslog-ng.conf
  1264. print_info "Added parameters to options block: ${missing_params[*]}"
  1265. fi
  1266. fi
  1267. fi
  1268. # Copy systemd service for Eye log processing
  1269. if [[ -f "/opt/Eye/docs/systemd/syslog-stat.service" ]]; then
  1270. cp /opt/Eye/docs/systemd/syslog-stat.service /etc/systemd/system/
  1271. chmod 644 /etc/systemd/system/syslog-stat.service
  1272. print_info "syslog-stat service copied"
  1273. fi
  1274. # Create log directory if it doesn't exist
  1275. mkdir -p /opt/Eye/scripts/log
  1276. chown eye:eye /opt/Eye/scripts/log
  1277. chmod 770 /opt/Eye/scripts/log
  1278. # Enable and start services
  1279. $SERVICE_MANAGER daemon-reload
  1280. if $SERVICE_MANAGER enable syslog-ng; then
  1281. print_info "syslog-ng service enabled for autostart"
  1282. else
  1283. print_warn "Failed to enable syslog-ng for autostart"
  1284. fi
  1285. if $SERVICE_MANAGER restart syslog-ng; then
  1286. print_info "syslog-ng service restarted"
  1287. else
  1288. print_warn "Failed to restart syslog-ng"
  1289. fi
  1290. if [[ -f "/etc/systemd/system/syslog-stat.service" ]]; then
  1291. if $SERVICE_MANAGER enable syslog-stat; then
  1292. print_info "syslog-stat service enabled for autostart"
  1293. else
  1294. print_warn "Failed to enable syslog-stat for autostart"
  1295. fi
  1296. if $SERVICE_MANAGER start syslog-stat; then
  1297. print_info "syslog-stat service started"
  1298. else
  1299. print_warn "Failed to start syslog-stat"
  1300. fi
  1301. fi
  1302. # Check syslog-ng configuration
  1303. if command -v syslog-ng &> /dev/null; then
  1304. if syslog-ng --syntax-only; then
  1305. print_info "syslog-ng configuration is valid"
  1306. else
  1307. print_error "Error in syslog-ng configuration"
  1308. print_warn "Check files: /etc/syslog-ng/syslog-ng.conf and /etc/syslog-ng/conf.d/eye.conf"
  1309. fi
  1310. fi
  1311. print_info "syslog-ng configuration completed"
  1312. print_info "To receive logs from devices, configure them to send to IP: $(hostname -f)"
  1313. }
  1314. # Configure additional services
  1315. setup_additional_services() {
  1316. print_step "Configuring additional services"
  1317. # stat-sync service
  1318. if [[ -f "/opt/Eye/docs/systemd/stat-sync.service" ]]; then
  1319. cp /opt/Eye/docs/systemd/stat-sync.service /etc/systemd/system/
  1320. $SERVICE_MANAGER enable stat-sync.service
  1321. print_info "stat-sync service enabled"
  1322. fi
  1323. # eye-statd service (NetFlow)
  1324. if [[ -f "/opt/Eye/docs/systemd/eye-statd.service" ]]; then
  1325. cp /opt/Eye/docs/systemd/eye-statd.service /etc/systemd/system/
  1326. $SERVICE_MANAGER enable eye-statd.service
  1327. print_info "eye-statd service (NetFlow) enabled"
  1328. fi
  1329. # add ipset
  1330. if [[ -f "/opt/Eye/docs/systemd/init.d/ipset" ]]; then
  1331. mkdir -p /etc/init.d
  1332. cp /opt/Eye/docs/systemd/init.d/ipset /etc/init.d
  1333. if [[ -f "/opt/Eye/docs/systemd/netfilter-persistent.service.d" ]]; then
  1334. if [[ "$OS_FAMILY" == "alt" ]]; then
  1335. mkdir -p /etc/systemd/system/iptables.service.d
  1336. cp /opt/Eye/docs/systemd/netfilter-persistent.service.d/override.conf /etc/systemd/system/iptables.service.d
  1337. else
  1338. mkdir -p /etc/systemd/system/netfilter-persistent.service.d
  1339. cp /opt/Eye/docs/systemd/netfilter-persistent.service.d/override.conf /etc/systemd/system/netfilter-persistent.service.d
  1340. fi
  1341. $SERVICE_MANAGER daemon-reload
  1342. fi
  1343. print_info "ipset installed"
  1344. fi
  1345. # Configure DHCP
  1346. setup_dhcp_server
  1347. # Configure syslog
  1348. setup_syslog
  1349. }
  1350. # Import MAC address database
  1351. import_mac_database() {
  1352. print_step "Importing MAC address database"
  1353. if [[ -f "/opt/Eye/scripts/utils/mac-oids/download-macs.sh" ]]; then
  1354. cd /opt/Eye/scripts/utils/mac-oids/
  1355. # Download MAC database
  1356. print_info "Downloading MAC address database..."
  1357. bash download-macs.sh
  1358. # Update vendors
  1359. if [[ -f "update-mac-vendors.pl" ]]; then
  1360. print_info "Updating vendor information..."
  1361. perl update-mac-vendors.pl
  1362. fi
  1363. cd - >/dev/null
  1364. else
  1365. print_warn "MAC address import scripts not found"
  1366. fi
  1367. }
  1368. # Final instructions
  1369. show_final_instructions() {
  1370. echo ""
  1371. echo -e "${GREEN}===========================================${NC}"
  1372. echo -e "${GREEN} INSTALLATION COMPLETED SUCCESSFULLY! ${NC}"
  1373. echo -e "${GREEN}===========================================${NC}"
  1374. echo ""
  1375. echo "SYSTEM INFORMATION:"
  1376. echo " Distribution: $OS_NAME"
  1377. echo " Version: $OS_VERSION"
  1378. echo " Database: $DB_TYPE"
  1379. echo " Language: $EYE_LANG"
  1380. echo " User: eye"
  1381. echo " Directory: /opt/Eye"
  1382. echo ""
  1383. echo ""
  1384. echo "TO COMPLETE SETUP, EXECUTE:"
  1385. echo ""
  1386. echo "1. Configure database security:"
  1387. if [[ "$DB_TYPE" == "postgresql" ]]; then
  1388. print_info " PostgreSQL: Edit pg_hba.conf if needed"
  1389. if [[ -f "/root/eye_postgres_password.txt" ]]; then
  1390. echo ""
  1391. echo "3. PostgreSQL 'stat' user password saved in:"
  1392. echo " /root/eye_postgres_password.txt"
  1393. echo ""
  1394. fi
  1395. else
  1396. echo " mysql_secure_installation"
  1397. if [[ -f "/root/eye_mysql_password.txt" ]]; then
  1398. echo ""
  1399. echo "3. MySQL 'stat' user password saved in:"
  1400. echo " /root/eye_mysql_password.txt"
  1401. echo ""
  1402. fi
  1403. fi
  1404. echo ""
  1405. echo "2. Check and edit configuration files:"
  1406. echo " /opt/Eye/html/cfg/config.php"
  1407. echo " /opt/Eye/scripts/cfg/config"
  1408. echo ""
  1409. echo "4. Configure cron jobs:"
  1410. echo " nano /etc/cron.d/eye"
  1411. echo " Uncomment required scripts"
  1412. echo ""
  1413. echo "5. Configure if necessary:"
  1414. echo " - DHCP: /etc/dnsmasq.conf"
  1415. echo " - NetFlow: configure on network devices"
  1416. echo ""
  1417. echo "6. WEB INTERFACE ACCESS:"
  1418. echo " URL: http://$(hostname -f)/"
  1419. echo " Admin: http://$(hostname -f)/admin/"
  1420. echo " Login: admin"
  1421. echo " Password: admin"
  1422. echo ""
  1423. echo -e "${RED}IMPORTANT:${NC}"
  1424. echo " - CHANGE admin password and API key!"
  1425. echo " - Configure users and networks in web interface"
  1426. echo ""
  1427. echo -e "${GREEN}===========================================${NC}"
  1428. echo ""
  1429. }
  1430. # Final instructions
  1431. show_final_upgrade() {
  1432. echo ""
  1433. echo -e "${GREEN}===========================================${NC}"
  1434. echo -e "${GREEN} UPGRADE COMPLETED SUCCESSFULLY! ${NC}"
  1435. echo -e "${GREEN}===========================================${NC}"
  1436. echo ""
  1437. }
  1438. # Install function
  1439. eye_install() {
  1440. clear
  1441. echo -e "${GREEN}===========================================${NC}"
  1442. echo -e "${GREEN} Installing Eye Monitoring System ${NC}"
  1443. echo -e "${GREEN} for ALT Linux/Debian/Ubuntu ${NC}"
  1444. echo -e "${GREEN}===========================================${NC}"
  1445. echo ""
  1446. # Инициализация глобальных переменных
  1447. DB_PASS=""
  1448. DB_TYPE="mysql"
  1449. EYE_LANG="russian"
  1450. EYE_LANG_SHORT="ru"
  1451. SQL_DATA_FILE=""
  1452. SQL_CREATE_FILE=""
  1453. INSTALL_TYPE="full"
  1454. DB_INSTALL="local"
  1455. # Обязательные шаги (всегда)
  1456. check_root
  1457. detect_distro
  1458. select_language
  1459. # Выбор типа установки (устанавливает INSTALL_TYPE, DB_INSTALL, DB_TYPE и параметры БД)
  1460. select_installation_type
  1461. # Обновление системы и установка пакетов (зависит от типа установки и ОС)
  1462. update_system
  1463. install_packages # ← внутри уже учитывает INSTALL_TYPE и DB_INSTALL
  1464. # Пользователь нужен всегда (для /opt/Eye)
  1465. create_user_group
  1466. # Установка исходного кода (учитывает INSTALL_TYPE)
  1467. install_source_code
  1468. # Настройка БД — ТОЛЬКО если локальная
  1469. if [[ "$DB_INSTALL" == "local" ]]; then
  1470. setup_database
  1471. fi
  1472. # Настройка конфигов — всегда (но внутри учитывает INSTALL_TYPE)
  1473. setup_configs
  1474. # Язык — только если установлен веб
  1475. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "web" ]]; then
  1476. apply_language_settings
  1477. fi
  1478. # Веб-сервер — только если нужен веб
  1479. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "web" ]]; then
  1480. setup_apache_php
  1481. fi
  1482. # Cron и logrotate — только если есть бэкенд (там — фоновые задачи и логи)
  1483. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
  1484. setup_cron_logrotate
  1485. fi
  1486. # Доп. сервисы (dnsmasq, syslog-ng и т.п.) — только для бэкенда
  1487. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
  1488. setup_additional_services
  1489. fi
  1490. # Импорт MAC-базы — только если есть бэкенд (он её использует)
  1491. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
  1492. import_mac_database
  1493. fi
  1494. show_final_instructions
  1495. }
  1496. backup_current_installation() {
  1497. print_step "Creating full backup of current Eye installation"
  1498. local EYE_ROOT="/opt/Eye"
  1499. local BACKUP_DIR="/opt"
  1500. local TIMESTAMP=$(date +"%Y-%m-%d_%H-%M-%S")
  1501. local BACKUP_FILE="$BACKUP_DIR/eye_backup_${TIMESTAMP}.tar.gz"
  1502. # Проверка: существует ли инсталляция
  1503. if [[ ! -d "$EYE_ROOT" ]]; then
  1504. print_warn "Directory $EYE_ROOT not found — skipping backup"
  1505. return 0
  1506. fi
  1507. # Проверка свободного места (~300 МБ на всякий случай)
  1508. local FREE_SPACE_KB=$(df "$BACKUP_DIR" | awk 'NR==2 {print $4}')
  1509. local MIN_FREE_KB=307200 # ~300 MB
  1510. if [[ $FREE_SPACE_KB -lt $MIN_FREE_KB ]]; then
  1511. print_error "Not enough free space in $BACKUP_DIR for full backup (need ~300 MB)"
  1512. return 1
  1513. fi
  1514. print_info "Creating full backup of $EYE_ROOT (excluding logs and docs)"
  1515. print_info "Backup file: $BACKUP_FILE"
  1516. # Архивируем ВЕСЬ /opt/Eye, но исключаем:
  1517. # - docs/ — не меняется, идёт с дистрибутивом
  1518. # - scripts/log/ — логи (большие, не конфигурация)
  1519. # - html/log/ — если есть
  1520. tar -czf "$BACKUP_FILE" \
  1521. --exclude="docs" \
  1522. --exclude="netflow" \
  1523. --exclude="scripts/log" \
  1524. --exclude="scripts/log/*" \
  1525. --exclude="html/log" \
  1526. --exclude="html/log/*" \
  1527. -C / "opt/Eye" 2>/dev/null
  1528. if [[ $? -eq 0 && -f "$BACKUP_FILE" ]]; then
  1529. print_info "✅ Backup completed successfully"
  1530. chmod 600 "$BACKUP_FILE"
  1531. chown root:root "$BACKUP_FILE"
  1532. else
  1533. print_error "❌ Failed to create backup archive"
  1534. return 1
  1535. fi
  1536. }
  1537. # Upgrade function
  1538. eye_upgrade() {
  1539. clear
  1540. echo -e "${GREEN}===========================================${NC}"
  1541. echo -e "${GREEN} Update Eye Monitoring System ${NC}"
  1542. echo -e "${GREEN}===========================================${NC}"
  1543. echo ""
  1544. check_root
  1545. detect_distro
  1546. stop_eye
  1547. backup_current_installation || {
  1548. echo "CRITICAL: Backup failed. Aborting upgrade."
  1549. start_eye
  1550. exit 1
  1551. }
  1552. update_system
  1553. install_packages
  1554. install_source_code
  1555. /opt/Eye/scripts/updates/upgrade.pl
  1556. import_mac_database
  1557. start_eye
  1558. show_final_upgrade
  1559. }
  1560. # Function to display help
  1561. show_help() {
  1562. echo "Usage: $0 [options]"
  1563. echo ""
  1564. echo "Options:"
  1565. echo " --help, -h Show this help"
  1566. echo " --upgrade, -u Automatic upgrade"
  1567. echo " --install, -i Interactive install"
  1568. echo ""
  1569. echo "Supported distributions:"
  1570. echo " - ALT Linux 11.1+"
  1571. echo " - Debian 11+"
  1572. echo " - Ubuntu 20.04+"
  1573. echo ""
  1574. }
  1575. # Function to check user existence
  1576. check_user() {
  1577. id "eye" &>/dev/null
  1578. return $?
  1579. }
  1580. # Function to check directory existence
  1581. check_directory() {
  1582. [ -d "/opt/Eye" ]
  1583. return $?
  1584. }
  1585. # Function to check if Eye config files exist
  1586. check_eye_configs() {
  1587. # Веб-конфиг
  1588. if [[ -f "/opt/Eye/html/cfg/config.php" ]]; then
  1589. return 0
  1590. fi
  1591. # Бэкенд-конфиг
  1592. if [[ -f "/opt/Eye/scripts/cfg/config" ]]; then
  1593. return 0
  1594. fi
  1595. return 1
  1596. }
  1597. # Handle command line arguments
  1598. case "$1" in
  1599. --help|-h)
  1600. show_help
  1601. exit 0
  1602. ;;
  1603. --upgrade|-u)
  1604. mode="upgrade"
  1605. echo "Mode set to: upgrade"
  1606. ;;
  1607. --install|-i)
  1608. mode="install"
  1609. echo "Mode set to: install"
  1610. ;;
  1611. *)
  1612. # Auto-detect mode
  1613. echo "Auto-detecting installation status..."
  1614. if check_user; then
  1615. user_exists=true
  1616. echo "✓ User 'eye' exists"
  1617. else
  1618. user_exists=false
  1619. echo "✗ User 'eye' does not exist"
  1620. fi
  1621. if check_directory; then
  1622. dir_exists=true
  1623. echo "✓ Directory /opt/Eye exists"
  1624. else
  1625. dir_exists=false
  1626. echo "✗ Directory /opt/Eye does not exist"
  1627. fi
  1628. # Проверяем наличие хотя бы одного конфига Eye
  1629. eye_config_found=false
  1630. if [[ -f "/opt/Eye/html/cfg/config.php" ]] || [[ -f "/opt/Eye/scripts/cfg/config" ]]; then
  1631. eye_config_found=true
  1632. echo "✓ Eye configuration detected"
  1633. fi
  1634. if $user_exists && $dir_exists && $eye_config_found; then
  1635. mode="upgrade"
  1636. echo "Existing Eye installation detected. Switching to upgrade mode."
  1637. # === Восстанавливаем INSTALL_TYPE ===
  1638. if [[ -f "/opt/Eye/html/cfg/config.php" ]] && [[ -f "/opt/Eye/scripts/cfg/config" ]]; then
  1639. INSTALL_TYPE="full"
  1640. elif [[ -f "/opt/Eye/html/cfg/config.php" ]]; then
  1641. INSTALL_TYPE="web"
  1642. elif [[ -f "/opt/Eye/scripts/cfg/config" ]]; then
  1643. INSTALL_TYPE="backend"
  1644. else
  1645. INSTALL_TYPE="full" # fallback
  1646. fi
  1647. # === Восстанавливаем DB_INSTALL (local/remote) ===
  1648. DB_HOST=""
  1649. if [[ -f "/opt/Eye/html/cfg/config.php" ]]; then
  1650. # Извлекаем DB_HOST из PHP-конфига
  1651. DB_HOST=$(grep -oP 'define\s*\(\s*"DB_HOST"\s*,\s*"\K[^"]+' /opt/Eye/html/cfg/config.php 2>/dev/null)
  1652. fi
  1653. if [[ -z "$DB_HOST" && -f "/opt/Eye/scripts/cfg/config" ]]; then
  1654. # Извлекаем из Perl-конфига
  1655. DB_HOST=$(grep -oP '^DBHOST=\K.*' /opt/Eye/scripts/cfg/config 2>/dev/null)
  1656. fi
  1657. if [[ "$DB_HOST" == "127.0.0.1" || "$DB_HOST" == "localhost" || "$DB_HOST" == "::1" ]]; then
  1658. DB_INSTALL="local"
  1659. else
  1660. DB_INSTALL="remote"
  1661. fi
  1662. # === Восстанавливаем DB_TYPE ===
  1663. if [[ -f "/opt/Eye/html/cfg/config.php" ]]; then
  1664. DB_TYPE=$(grep -oP 'define\s*\(\s*"DB_TYPE"\s*,\s*"\K[^"]+' /opt/Eye/html/cfg/config.php 2>/dev/null)
  1665. # В PHP может быть 'pgsql' вместо 'postgresql'
  1666. if [[ "$DB_TYPE" == "pgsql" ]]; then
  1667. DB_TYPE="postgresql"
  1668. elif [[ "$DB_TYPE" == "mysql" ]]; then
  1669. DB_TYPE="mysql"
  1670. fi
  1671. elif [[ -f "/opt/Eye/scripts/cfg/config" ]]; then
  1672. DB_TYPE=$(grep -oP '^DBTYPE=\K.*' /opt/Eye/scripts/cfg/config 2>/dev/null)
  1673. fi
  1674. # Защита от неопределённых значений
  1675. : "${INSTALL_TYPE:=full}"
  1676. : "${DB_INSTALL:=remote}"
  1677. : "${DB_TYPE:=mysql}"
  1678. echo " → INSTALL_TYPE = $INSTALL_TYPE"
  1679. echo " → DB_INSTALL = $DB_INSTALL"
  1680. echo " → DB_TYPE = $DB_TYPE"
  1681. else
  1682. mode="install"
  1683. echo "No existing Eye installation found. Switching to install mode."
  1684. fi
  1685. ;;
  1686. esac
  1687. echo ""
  1688. echo "Selected mode: $mode"
  1689. # Main execution based on mode
  1690. case "$mode" in
  1691. "upgrade")
  1692. echo "Starting upgrade process..."
  1693. # Start upgrade
  1694. eye_upgrade
  1695. ;;
  1696. "install")
  1697. echo "Starting installation process..."
  1698. # Start installation
  1699. eye_install
  1700. ;;
  1701. *)
  1702. echo "Error: Unknown mode '$mode'"
  1703. exit 1
  1704. ;;
  1705. esac
  1706. # Exit with success code
  1707. exit 0