install-eye.sh 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979
  1. #!/bin/bash
  2. # Eye Installation Script for ALT Linux/Debian/Ubuntu with PostgreSQL support
  3. # Version: 2.1
  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. local PHP_VERSION
  68. PHP_VERSION=$(php -v 2>/dev/null | head -n1 | grep -oP '\d+\.\d+' || echo "")
  69. if [ -n "${PHP_VERSION}" ]; then
  70. safe_start_service "php${PHP_VERSION}-fpm"
  71. fi
  72. for svc in cron eye-statd dhcp-log stat-sync syslog-stat; do
  73. safe_start_service "$svc"
  74. done
  75. }
  76. # Detect distribution and package manager
  77. detect_distro() {
  78. if [[ -f /etc/os-release ]]; then
  79. . /etc/os-release
  80. OS_ID=$ID
  81. OS_VERSION=$VERSION_ID
  82. OS_NAME=$NAME
  83. case $OS_ID in
  84. altlinux)
  85. PACKAGE_MANAGER="apt-get"
  86. SERVICE_MANAGER="systemctl"
  87. OS_FAMILY="alt"
  88. print_info "Detected ALT Linux $OS_VERSION"
  89. ;;
  90. debian)
  91. PACKAGE_MANAGER="apt"
  92. SERVICE_MANAGER="systemctl"
  93. OS_FAMILY="debian"
  94. print_info "Detected Debian $OS_VERSION"
  95. ;;
  96. ubuntu)
  97. PACKAGE_MANAGER="apt"
  98. SERVICE_MANAGER="systemctl"
  99. OS_FAMILY="debian"
  100. print_info "Detected Ubuntu $OS_VERSION"
  101. ;;
  102. *)
  103. print_error "Unsupported distribution: $OS_ID"
  104. print_error "Supported: ALT Linux, Debian, Ubuntu"
  105. exit 1
  106. ;;
  107. esac
  108. else
  109. print_error "Failed to detect distribution"
  110. exit 1
  111. fi
  112. }
  113. select_language() {
  114. print_step "Select Installation Language"
  115. echo "Available languages:"
  116. echo "1) English"
  117. echo "2) Russian (default)"
  118. echo ""
  119. while true; do
  120. read -p "Select language (1 or 2) [2]: " lang_choice
  121. # Если пустой ввод - по умолчанию английский
  122. if [[ -z "$lang_choice" ]]; then
  123. lang_choice="2"
  124. fi
  125. # Обработка ввода (приводим к нижнему регистру)
  126. lang_choice_lower=$(echo "$lang_choice" | tr '[:upper:]' '[:lower:]')
  127. case $lang_choice_lower in
  128. 1|english|en|eng|анг|английский)
  129. EYE_LANG="english"
  130. EYE_LANG_SHORT="en"
  131. print_info "Selected English language"
  132. break
  133. ;;
  134. 2|russian|ru|rus|ру|русский)
  135. EYE_LANG="russian"
  136. EYE_LANG_SHORT="ru"
  137. print_info "Selected Russian language (Русский)"
  138. break
  139. ;;
  140. *)
  141. print_error "Invalid choice: '$lang_choice'"
  142. print_warn "Available options: 1 (English), 2 (Russian)"
  143. print_warn "You can also type: english, en, russian, ru"
  144. ;;
  145. esac
  146. done
  147. }
  148. # Ask user for database type
  149. select_database_type() {
  150. print_step "Select Database Type"
  151. echo "Available database types:"
  152. echo "1) MySQL/MariaDB (default)"
  153. echo "2) PostgreSQL"
  154. echo ""
  155. read -p "Select database type (1 or 2) [1]: " db_choice
  156. case $db_choice in
  157. 2|postgres|postgresql|pgsql)
  158. DB_TYPE="postgresql"
  159. print_info "Selected PostgreSQL"
  160. ;;
  161. *)
  162. DB_TYPE="mysql"
  163. print_info "Selected MySQL/MariaDB"
  164. ;;
  165. esac
  166. }
  167. # Настройка параметров подключения к БД (общая для local и remote)
  168. configure_database_connection() {
  169. echo ""
  170. if [[ "$DB_INSTALL" == "local" ]]; then
  171. echo "Local Database Configuration"
  172. echo "============================"
  173. DB_HOST="127.0.0.1"
  174. if [[ "$DB_TYPE" == "postgresql" ]]; then
  175. DB_PORT="5432"
  176. else
  177. DB_PORT="3306"
  178. fi
  179. echo "Database server: $DB_HOST:$DB_PORT (local)"
  180. else
  181. echo "Remote Database Configuration"
  182. echo "============================"
  183. read -p "Database server IP address: " DB_HOST
  184. read -p "Database port [$([ "$DB_TYPE" == "postgresql" ] && echo "5432" || echo "3306")]: " DB_PORT
  185. # Установка порта по умолчанию, если не введён
  186. if [[ -z "$DB_PORT" ]]; then
  187. if [[ "$DB_TYPE" == "postgresql" ]]; then
  188. DB_PORT="5432"
  189. else
  190. DB_PORT="3306"
  191. fi
  192. fi
  193. fi
  194. read -p "Database name [stat]: " DB_NAME
  195. read -p "Database username [stat]: " DB_USER
  196. echo ""
  197. # Установка значений по умолчанию
  198. : "${DB_NAME:=stat}"
  199. : "${DB_USER:=stat}"
  200. }
  201. # Function for installation type selection
  202. select_installation_type() {
  203. echo "Select installation type:"
  204. echo "1. Web interface + network backend"
  205. echo "2. Web interface only"
  206. echo "3. Network backend only"
  207. echo ""
  208. read -p "Enter selection number [1]: " install_type
  209. case $install_type in
  210. 1)
  211. INSTALL_TYPE="full"
  212. echo "Selected: Web interface + network backend"
  213. read -p "Install database locally? (y/n) [y]: " install_db
  214. if [[ -z "$install_db" || "$install_db" =~ ^[Yy]$ ]]; then
  215. DB_INSTALL="local"
  216. echo "Local database will be installed"
  217. select_database_type
  218. else
  219. DB_INSTALL="remote"
  220. echo "Remote database configuration"
  221. select_database_type
  222. fi
  223. configure_database_connection
  224. ;;
  225. 2)
  226. INSTALL_TYPE="web"
  227. echo "Selected: Web interface only"
  228. DB_INSTALL="remote"
  229. select_database_type
  230. configure_database_connection
  231. ;;
  232. 3)
  233. INSTALL_TYPE="backend"
  234. echo "Selected: Network backend only"
  235. DB_INSTALL="remote"
  236. select_database_type
  237. configure_database_connection
  238. ;;
  239. *)
  240. INSTALL_TYPE="full"
  241. echo "Default selected: Web interface + network backend"
  242. DB_INSTALL="local"
  243. echo "Local database will be installed"
  244. select_database_type
  245. configure_database_connection
  246. ;;
  247. esac
  248. # Защита от неопределённых переменных
  249. : "${DB_TYPE:=mysql}"
  250. : "${DB_INSTALL:=local}"
  251. : "${DB_HOST:=127.0.0.1}"
  252. : "${DB_NAME:=stat}"
  253. : "${DB_USER:=stat}"
  254. }
  255. # Install dependencies for ALT Linux
  256. install_deps_altlinux() {
  257. print_step "Installing dependencies for ALT Linux"
  258. apt-get update
  259. # Общие утилиты (всегда нужны)
  260. apt-get install -y git wget rsync xxd hwdata pwgen
  261. # === Локальная база данных (если выбрана) ===
  262. if [[ "$DB_INSTALL" == "local" ]]; then
  263. if [[ "$DB_TYPE" == "postgresql" ]]; then
  264. apt-get install -y postgresql17 postgresql17-server postgresql17-contrib postgresql17-perl
  265. else
  266. apt-get install -y mariadb-server mariadb-client
  267. fi
  268. fi
  269. # === Веб-интерфейс (если нужен) ===
  270. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "web" ]]; then
  271. apt-get install -y apache2 php8.2 php8.2-fpm-fcgi apache2-mod_fcgid \
  272. php8.2-intl php8.2-mbstring php8.2-snmp php8.2-zip pear-Mail
  273. if [[ "$DB_TYPE" == "postgresql" ]]; then
  274. apt-get install -y php8.2-pgsql php8.2-pdo_pgsql
  275. else
  276. apt-get install -y php8.2-mysqlnd php8.2-pdo_mysql php8.2-mysqlnd-mysqli
  277. fi
  278. fi
  279. # === Сетевой бэкенд (если нужен) ===
  280. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
  281. apt-get install -y fping
  282. # Общие Perl-модули (независимо от СУБД)
  283. apt-get install -y perl \
  284. perl-Net-Patricia perl-NetAddr-IP perl-Config-Tiny \
  285. perl-Net-DNS perl-DateTime perl-Net-Ping \
  286. perl-Net-Netmask perl-Text-Iconv perl-Net-SNMP \
  287. perl-Net-Telnet perl-DBI \
  288. perl-Parallel-ForkManager perl-Proc-Daemon \
  289. perl-DateTime-Format-DateParse perl-DateTime-Format-Strptime \
  290. perl-Net-OpenSSH perl-File-Tail perl-Tie-File \
  291. perl-Crypt-Rijndael perl-Crypt-CBC perl-CryptX perl-Crypt-DES \
  292. perl-File-Path-Tiny perl-Expect perl-Proc-ProcessTable \
  293. perl-Text-CSV \
  294. perl-DBD-Pg perl-DBD-mysql
  295. fi
  296. # Дополнительные проверки (например, fping — нужны только бэкенду)
  297. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
  298. control fping public
  299. fi
  300. control ping public
  301. }
  302. # Install dependencies for Debian/Ubuntu
  303. install_deps_debian() {
  304. print_step "Installing dependencies for Debian/Ubuntu"
  305. apt-get update
  306. # Общие утилиты (всегда нужны)
  307. apt-get install -y git wget rsync xxd hwdata pwgen bsdmainutils
  308. # === Локальная база данных (если выбрана) ===
  309. if [[ "$DB_INSTALL" == "local" ]]; then
  310. if [[ "$DB_TYPE" == "postgresql" ]]; then
  311. # Устанавливаем generic-пакеты PostgreSQL
  312. apt-get install -y postgresql postgresql-contrib postgresql-server-dev-all
  313. else
  314. apt-get install -y mariadb-server mariadb-client
  315. fi
  316. fi
  317. # === Веб-интерфейс (если нужен) ===
  318. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "web" ]]; then
  319. apt-get install -y apache2 libapache2-mod-fcgid \
  320. php php-fpm \
  321. php-bcmath php-intl php-mbstring php-snmp php-zip php-mail \
  322. php-date php-db
  323. if [[ "$DB_TYPE" == "postgresql" ]]; then
  324. apt-get install -y php-pgsql
  325. else
  326. apt-get install -y php-mysql
  327. fi
  328. fi
  329. # === Сетевой бэкенд (если нужен) ===
  330. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
  331. apt-get install -y fping
  332. # Perl и обязательные модули (имена корректны для Ubuntu 24.04)
  333. apt-get install -y perl \
  334. libnet-patricia-perl libnetaddr-ip-perl libconfig-tiny-perl \
  335. libnet-dns-perl libdatetime-perl libnet-netmask-perl \
  336. libtext-iconv-perl libnet-snmp-perl libnet-telnet-perl \
  337. libdbi-perl libparallel-forkmanager-perl libproc-daemon-perl \
  338. libdatetime-format-dateparse-perl libnetwork-ipv4addr-perl \
  339. libnet-openssh-perl libfile-tail-perl libdatetime-format-strptime-perl \
  340. libcrypt-rijndael-perl libcrypt-cbc-perl libcryptx-perl \
  341. libcrypt-des-perl libfile-path-tiny-perl libexpect-perl \
  342. libtext-csv-perl \
  343. libdbd-pg-perl libdbd-mysql-perl
  344. fi
  345. # === Дополнительно (если нужно) ===
  346. # Раскомментируйте, если требуется DNS-сервер
  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. print_info "Importing database structure..."
  658. # Import main SQL file
  659. mysql $MYSQL_OPT <<EOF
  660. CREATE DATABASE IF NOT EXISTS ${DB_NAME} DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
  661. EOF
  662. mysql $MYSQL_OPT ${DB_NAME} < ${SQL_CREATE_FILE}
  663. if [[ $? -ne 0 ]]; then
  664. print_error "Error importing create_db.sql"
  665. if [[ -f "$MYSQL_CNF_FILE" ]]; then
  666. rm -f "$MYSQL_CNF_FILE"
  667. fi
  668. return 1
  669. fi
  670. print_info "Database structure imported"
  671. # Import data
  672. print_info "Importing initial data..."
  673. mysql $MYSQL_OPT ${DB_NAME} < ${SQL_DATA_FILE}
  674. if [[ $? -ne 0 ]]; then
  675. print_warn "Error importing data.sql (data may already exist)"
  676. else
  677. print_info "Initial data imported"
  678. fi
  679. # Create db user
  680. print_info "Creating user ${DB_USER}.."
  681. mysql $MYSQL_OPT <<EOF
  682. CREATE USER IF NOT EXISTS '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASS';
  683. GRANT ALL PRIVILEGES ON $DB_NAME.* TO '$DB_USER'@'localhost';
  684. FLUSH PRIVILEGES;
  685. EOF
  686. if [[ $? -ne 0 ]]; then
  687. print_error "Error creating user $DB_USER"
  688. if [[ -f "$MYSQL_CNF_FILE" ]]; then
  689. rm -f "$MYSQL_CNF_FILE"
  690. fi
  691. return 1
  692. fi
  693. print_info "User $DB_USER successfully created"
  694. # Save password information
  695. echo "MySQL $DB_USER user password: $DB_PASS" > /root/eye_mysql_password.txt
  696. chmod 600 /root/eye_mysql_password.txt
  697. print_info "User $DB_USER password: $DB_PASS"
  698. print_warn "Password saved in /root/eye_mysql_password.txt"
  699. # Clean up temporary file if created
  700. if [[ -f "$MYSQL_CNF_FILE" ]]; then
  701. rm -f "$MYSQL_CNF_FILE"
  702. fi
  703. return 0
  704. }
  705. # Configure PostgreSQL
  706. setup_postgresql() {
  707. print_step "Configuring PostgreSQL"
  708. PGDATA="/var/lib/pgsql/data"
  709. # Для ALT Linux
  710. if [[ "$OS_FAMILY" == "alt" ]]; then
  711. echo "root ALL=(ALL:ALL) NOPASSWD: ALL" >/etc/sudoers.d/root
  712. PGDATA="/var/lib/pgsql/data"
  713. if [ -z "$(ls -A $PGDATA 2>/dev/null)" ]; then
  714. /etc/init.d/postgresql initdb
  715. # === ВАЖНО: настраиваем pg_hba.conf для безпарольного доступа ===
  716. local pg_hba_file="$PGDATA/pg_hba.conf"
  717. if [[ -f "$pg_hba_file" ]]; then
  718. # Делаем резервную копию
  719. cp "$pg_hba_file" "${pg_hba_file}.backup"
  720. # Вставляем правило для пользователя 'postgres' в начало файла
  721. # Это разрешит подключение без пароля через Unix-сокет
  722. sed -i '1i\
  723. # Allow local postgres user without password\
  724. local all postgres peer\
  725. ' "$pg_hba_file"
  726. print_info "Configured pg_hba.conf to allow peer authentication for 'postgres'"
  727. fi
  728. fi
  729. # Start and enable service
  730. $SERVICE_MANAGER enable postgresql
  731. $SERVICE_MANAGER restart postgresql
  732. else
  733. # Start and enable service
  734. $SERVICE_MANAGER enable postgresql
  735. $SERVICE_MANAGER start postgresql
  736. fi
  737. # Check PostgreSQL access
  738. if ! command -v psql &> /dev/null; then
  739. print_error "PostgreSQL client not installed"
  740. return 1
  741. fi
  742. # Спросить, создавать ли БД
  743. read -p "Create database and user for Eye? (y/n): " -n 1 -r
  744. echo
  745. if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  746. print_warn "Database creation skipped. Create manually as postgres user:"
  747. print_warn " sudo -u postgres createdb -O $DB_USER $DB_NAME"
  748. print_warn " sudo -u postgres psql -d $DB_NAME -f $SQL_DATA_FILE"
  749. return 0
  750. fi
  751. # Генерация пароля для пользователя БД
  752. if command -v pwgen &> /dev/null; then
  753. DB_PASS=$(pwgen 16 1)
  754. else
  755. DB_PASS=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c16)
  756. fi
  757. # Определяем локаль на основе языка
  758. if [[ "$EYE_LANG" == "russian" ]]; then
  759. LC_TYPE="ru_RU.UTF-8"
  760. else
  761. LC_TYPE="en_US.UTF-8"
  762. fi
  763. print_info "Creating database '$DB_NAME' with locale '$LC_TYPE'..."
  764. # Set password for stat user
  765. print_info "Setting password for user $DB_USER ..."
  766. sudo -u postgres psql -c "CREATE USER $DB_USER WITH PASSWORD '$DB_PASS';"
  767. sudo -u postgres createdb \
  768. --encoding=UTF8 \
  769. --lc-collate="$LC_TYPE" \
  770. --lc-ctype="$LC_TYPE" \
  771. --template=template0 \
  772. --owner="$DB_USER" \
  773. "$DB_NAME"
  774. if [[ $? -ne 0 ]]; then
  775. print_error "Failed to create database"
  776. return 1
  777. fi
  778. print_info "Database created successfully with owner '$DB_USER'"
  779. sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;"
  780. # Теперь подключаемся как новый владелец для импорта
  781. print_info "Importing database structure as '$DB_USER'..."
  782. # Вариант 1: Используя sudo и переключение пользователя в psql
  783. sudo -u postgres psql -d "$DB_NAME" <<EOF
  784. SET ROLE "$DB_USER";
  785. \i $SQL_CREATE_FILE
  786. EOF
  787. if [[ $? -ne 0 ]]; then
  788. print_error "Error importing create_db.sql"
  789. return 1
  790. fi
  791. print_info "Database structure imported successfully"
  792. # Импортируем данные тоже как владелец
  793. if [[ -f "$SQL_DATA_FILE" ]]; then
  794. print_info "Importing database data as '$DB_USER'..."
  795. sudo -u postgres psql -d "$DB_NAME" <<EOF
  796. SET ROLE "$DB_USER";
  797. \i $SQL_DATA_FILE
  798. EOF
  799. if [[ $? -ne 0 ]]; then
  800. print_warn "Warning: failed to import data (may already exist or non-critical)"
  801. else
  802. print_info "Database data imported successfully"
  803. fi
  804. fi
  805. # Дополнительные привилегии
  806. print_info "Setting up additional privileges..."
  807. # Дать доступ пользователю postgres к БД
  808. sudo -u postgres psql -c "GRANT CONNECT ON DATABASE $DB_NAME TO postgres;"
  809. # Дать полные права пользователю postgres на все объекты
  810. sudo -u postgres psql -d "$DB_NAME" <<EOF
  811. GRANT ALL ON SCHEMA public TO postgres;
  812. ALTER DEFAULT PRIVILEGES FOR USER "$DB_USER" IN SCHEMA public GRANT ALL ON TABLES TO postgres;
  813. ALTER DEFAULT PRIVILEGES FOR USER "$DB_USER" IN SCHEMA public GRANT ALL ON SEQUENCES TO postgres;
  814. ALTER DEFAULT PRIVILEGES FOR USER "$DB_USER" IN SCHEMA public GRANT ALL ON FUNCTIONS TO postgres;
  815. EOF
  816. print_info "Database setup completed successfully"
  817. # Configure PostgreSQL for MD5 authentication
  818. if [[ "$OS_FAMILY" == "alt" ]]; then
  819. local pg_hba_file="/var/lib/pgsql/data/pg_hba.conf"
  820. if [[ -f "$pg_hba_file" ]]; then
  821. # Backup original
  822. cp "$pg_hba_file" "${pg_hba_file}.backup"
  823. # Add local md5 authentication if not present
  824. if ! grep -q "local.*$DB_NAME.*md5" "$pg_hba_file"; then
  825. echo "local $DB_NAME $DB_USER scram-sha-256" >> "$pg_hba_file"
  826. print_info "Added MD5 authentication for $DB_USER user in pg_hba.conf"
  827. fi
  828. fi
  829. else
  830. local pg_hba_file="/etc/postgresql/$(ls /etc/postgresql/ | head -1)/main/pg_hba.conf"
  831. if [[ -f "$pg_hba_file" ]]; then
  832. # Backup original
  833. cp "$pg_hba_file" "${pg_hba_file}.backup"
  834. # Add local md5 authentication if not present
  835. if ! grep -q "local.*$DB_NAME.*md5" "$pg_hba_file"; then
  836. echo "local $DB_NAME $DB_USER scram-sha-256" >> "$pg_hba_file"
  837. print_info "Added MD5 authentication for $DB_USER user in pg_hba.conf"
  838. fi
  839. fi
  840. fi
  841. # Restart PostgreSQL to apply changes
  842. $SERVICE_MANAGER restart postgresql
  843. # Save password information
  844. echo "PostgreSQL $DB_USER user password: $DB_PASS" > /root/eye_postgres_password.txt
  845. chmod 600 /root/eye_postgres_password.txt
  846. print_info "User $DB_USER password: $DB_PASS"
  847. print_warn "Password saved in /root/eye_postgres_password.txt"
  848. return 0
  849. }
  850. # Configure database based on selected type
  851. setup_database() {
  852. # Пропускаем настройку, если БД — удалённая
  853. if [[ "$DB_INSTALL" != "local" ]]; then
  854. print_info "Database is configured remotely — skipping local setup"
  855. return 0
  856. fi
  857. print_step "Setting up local database"
  858. # Определяем пути к SQL-файлам в зависимости от типа БД и языка
  859. if [[ "$DB_TYPE" == "mysql" ]]; then
  860. if [[ "$EYE_LANG" == "russian" && -d "/opt/Eye/docs/databases/mysql/ru" ]]; then
  861. SQL_DATA_FILE="/opt/Eye/docs/databases/mysql/ru/data.sql"
  862. SQL_CREATE_FILE="/opt/Eye/docs/databases/mysql/ru/create_db.sql"
  863. else
  864. SQL_DATA_FILE="/opt/Eye/docs/databases/mysql/en/data.sql"
  865. SQL_CREATE_FILE="/opt/Eye/docs/databases/mysql/en/create_db.sql"
  866. fi
  867. elif [[ "$DB_TYPE" == "postgresql" ]]; then
  868. if [[ "$EYE_LANG" == "russian" && -d "/opt/Eye/docs/databases/postgres/ru" ]]; then
  869. SQL_DATA_FILE="/opt/Eye/docs/databases/postgres/ru/data.sql"
  870. SQL_CREATE_FILE="/opt/Eye/docs/databases/postgres/ru/create_db.sql"
  871. else
  872. SQL_DATA_FILE="/opt/Eye/docs/databases/postgres/en/data.sql"
  873. SQL_CREATE_FILE="/opt/Eye/docs/databases/postgres/en/create_db.sql"
  874. fi
  875. else
  876. print_error "Unsupported database type: $DB_TYPE"
  877. return 1
  878. fi
  879. # Проверка существования файлов
  880. if [[ ! -f "$SQL_CREATE_FILE" || ! -f "$SQL_DATA_FILE" ]]; then
  881. print_error "SQL files not found for DB_TYPE=$DB_TYPE and EYE_LANG=$EYE_LANG"
  882. return 1
  883. fi
  884. print_info "Using SQL files for $EYE_LANG language"
  885. # Выполняем настройку в зависимости от СУБД
  886. if [[ "$DB_TYPE" == "postgresql" ]]; then
  887. setup_postgresql
  888. else
  889. setup_mysql
  890. fi
  891. }
  892. # Configure configuration files
  893. setup_configs() {
  894. print_step "Configuring configuration files"
  895. # Генерация или запрос ключей шифрования
  896. print_info "Setting up encryption keys..."
  897. if [[ "$DB_INSTALL" == "local" ]]; then
  898. # Для локальной БД — генерируем автоматически
  899. if command -v pwgen &> /dev/null; then
  900. ENC_PASSWORD=$(pwgen 16 1)
  901. else
  902. ENC_PASSWORD=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c16)
  903. fi
  904. ENC_VECTOR=$(tr -dc 0-9 </dev/urandom | head -c 16)
  905. print_info "Encryption keys generated automatically (local database)."
  906. print_info "Password: $ENC_PASSWORD"
  907. print_info "Vector: $ENC_VECTOR"
  908. else
  909. # Для удалённой БД — ОБЯЗАТЕЛЬНО запрашиваем у пользователя
  910. echo ""
  911. print_info "Remote database detected. You MUST provide the encryption keys"
  912. print_info "that are already in use by other Eye components connected to this database."
  913. echo ""
  914. while [[ -z "$ENC_PASSWORD" ]]; do
  915. read -p "Enter ENCRYPTION_KEY (16+ characters): " ENC_PASSWORD
  916. if [[ ${#ENC_PASSWORD} -lt 16 ]]; then
  917. print_warn "Key should be at least 16 characters long."
  918. ENC_PASSWORD=""
  919. fi
  920. done
  921. while [[ -z "$ENC_VECTOR" ]]; do
  922. read -p "Enter ENCRYPTION_IV (exactly 16 digits): " ENC_VECTOR
  923. if [[ ! "$ENC_VECTOR" =~ ^[0-9]{16}$ ]]; then
  924. print_warn "IV must consist of exactly 16 digits (0-9)."
  925. ENC_VECTOR=""
  926. fi
  927. done
  928. print_info "Encryption keys accepted for remote database."
  929. fi
  930. # === Настройка веб-конфигурации (только если нужен веб) ===
  931. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "web" ]]; then
  932. if [[ -f "/opt/Eye/html/cfg/config.sample.php" ]]; then
  933. cp /opt/Eye/html/cfg/config.sample.php /opt/Eye/html/cfg/config.php
  934. # Определяем DB_TYPE для PHP (mysql или pgsql)
  935. PHP_DB_TYPE="$DB_TYPE"
  936. [[ "$DB_TYPE" == "postgresql" ]] && PHP_DB_TYPE="pgsql"
  937. # Подстановка реальных значений
  938. sed -i "s/define(\"DB_TYPE\",\"[^\"]*\");/define(\"DB_TYPE\",\"$PHP_DB_TYPE\");/" /opt/Eye/html/cfg/config.php
  939. sed -i "s/define(\"DB_HOST\",\"[^\"]*\");/define(\"DB_HOST\",\"$DB_HOST\");/" /opt/Eye/html/cfg/config.php
  940. sed -i "s/define(\"DB_PORT\",\"[^\"]*\");/define(\"DB_PORT\",\"$DB_PORT\");/" /opt/Eye/html/cfg/config.php
  941. sed -i "s/define(\"DB_NAME\",\"[^\"]*\");/define(\"DB_NAME\",\"$DB_NAME\");/" /opt/Eye/html/cfg/config.php
  942. sed -i "s/define(\"DB_USER\",\"[^\"]*\");/define(\"DB_USER\",\"$DB_USER\");/" /opt/Eye/html/cfg/config.php
  943. sed -i "s/define(\"DB_PASS\",\"[^\"]*\");/define(\"DB_PASS\",\"$DB_PASS\");/" /opt/Eye/html/cfg/config.php
  944. # Ключи шифрования
  945. sed -i "s/ENCRYPTION_KEY\",\"[^\"]*\"/ENCRYPTION_KEY\",\"$ENC_PASSWORD\"/" /opt/Eye/html/cfg/config.php
  946. sed -i "s/ENCRYPTION_IV\",\"[^\"]*\"/ENCRYPTION_IV\",\"$ENC_VECTOR\"/" /opt/Eye/html/cfg/config.php
  947. print_info "Web configuration file config.php created"
  948. else
  949. print_warn "Web config template not found, skipping PHP config"
  950. fi
  951. fi
  952. # === Настройка конфигурации бэкенда (только если нужен бэкенд) ===
  953. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
  954. if [[ -f "/opt/Eye/scripts/cfg/config.sample" ]]; then
  955. cp /opt/Eye/scripts/cfg/config.sample /opt/Eye/scripts/cfg/config
  956. # Подстановка значений
  957. sed -i "s/^DBTYPE=.*/DBTYPE=$DB_TYPE/" /opt/Eye/scripts/cfg/config
  958. sed -i "s/DBTYPE=db_type/DBTYPE=$DB_TYPE/" /opt/Eye/scripts/cfg/config
  959. sed -i "s/^DBHOST=.*/DBHOST=$DB_HOST/" /opt/Eye/scripts/cfg/config
  960. sed -i "s/^DBPORT=.*/DBPORT=$DB_PORT/" /opt/Eye/scripts/cfg/config
  961. sed -i "s/^DBNAME=.*/DBNAME=$DB_NAME/" /opt/Eye/scripts/cfg/config
  962. sed -i "s/^DBUSER=.*/DBUSER=$DB_USER/" /opt/Eye/scripts/cfg/config
  963. sed -i "s/^DBPASS=.*/DBPASS=$DB_PASS/" /opt/Eye/scripts/cfg/config
  964. # Ключи шифрования
  965. sed -i "s/^encryption_key=.*/encryption_key=$ENC_PASSWORD/" /opt/Eye/scripts/cfg/config
  966. sed -i "s/encryption_key=!!!CHANGE_ME!!!!/encryption_key=$ENC_PASSWORD/" /opt/Eye/scripts/cfg/config
  967. sed -i "s/^encryption_iv=.*/encryption_iv=$ENC_VECTOR/" /opt/Eye/scripts/cfg/config
  968. sed -i "s/encryption_iv=0123456789012345/encryption_iv=$ENC_VECTOR/" /opt/Eye/scripts/cfg/config
  969. print_info "Backend configuration file scripts/cfg/config created"
  970. else
  971. print_warn "Backend config template not found, skipping scripts config"
  972. fi
  973. fi
  974. # === Установка прав (только для существующих каталогов) ===
  975. if [[ -d "/opt/Eye/html/cfg" ]]; then
  976. chown -R eye:eye /opt/Eye/html/cfg
  977. chmod 750 /opt/Eye/html/cfg
  978. chmod 660 /opt/Eye/html/cfg/config.php 2>/dev/null || true
  979. fi
  980. if [[ -d "/opt/Eye/scripts/cfg" ]]; then
  981. chown -R eye:eye /opt/Eye/scripts/cfg
  982. chmod 750 /opt/Eye/scripts/cfg
  983. chmod 660 /opt/Eye/scripts/cfg/config 2>/dev/null || true
  984. fi
  985. }
  986. # Функция применения языковых настроек к конфигурации
  987. apply_language_settings() {
  988. print_info "Applying language settings: $EYE_LANG"
  989. # Применяем языковые настройки только если установлен веб-интерфейс
  990. if [[ "$INSTALL_TYPE" != "web" && "$INSTALL_TYPE" != "full" ]]; then
  991. print_info "Web interface not installed — skipping language configuration"
  992. return 0
  993. fi
  994. # Проверяем, существует ли каталог конфигурации веба
  995. if [[ ! -d "/opt/Eye/html/cfg" ]]; then
  996. print_warn "Web config directory not found — skipping language setup"
  997. return 0
  998. fi
  999. CONFIG_PHP="/opt/Eye/html/cfg/config.php"
  1000. if [[ ! -f "$CONFIG_PHP" ]]; then
  1001. print_warn "Web config file not found — skipping language setup"
  1002. return 0
  1003. fi
  1004. if [[ "$EYE_LANG" == "russian" ]]; then
  1005. # Установка русского языка
  1006. sed -i "s/define(\"HTML_LANG\",\"[^\"]*\"\");/define(\"HTML_LANG\",\"russian\");/g" "$CONFIG_PHP"
  1007. sed -i "s/setlocale(LC_ALL, '[^']*');/setlocale(LC_ALL, 'ru_RU.UTF-8');/g" "$CONFIG_PHP"
  1008. print_info "Web interface language set to Russian"
  1009. else
  1010. # Установка английского языка (по умолчанию)
  1011. sed -i "s/define(\"HTML_LANG\",\"[^\"]*\"\");/define(\"HTML_LANG\",\"english\");/g" "$CONFIG_PHP"
  1012. sed -i "s/setlocale(LC_ALL, '[^']*');/setlocale(LC_ALL, 'en_US.UTF-8');/g" "$CONFIG_PHP"
  1013. print_info "Web interface language set to English"
  1014. fi
  1015. }
  1016. # Configure Apache and PHP
  1017. setup_apache_php() {
  1018. print_step "Configuring Apache and PHP"
  1019. # Determine PHP version
  1020. PHP_VERSION=$(php -v 2>/dev/null | head -n1 | grep -oP '\d+\.\d+' || echo "8.2")
  1021. echo "Версия PHP: $PHP_VERSION"
  1022. # Configure PHP for all distributions
  1023. if [[ "$OS_FAMILY" == "alt" ]]; then
  1024. # ALT Linux
  1025. PHP_INI="/etc/php/$PHP_VERSION/apache2/php.ini"
  1026. APACHE_CONF_DIR="/etc/httpd2/conf"
  1027. APACHE_SITES_DIR="$APACHE_CONF_DIR/sites-available"
  1028. DEFAULT_CONF="$APACHE_SITES_DIR/000-default.conf"
  1029. APACHE_USER="apache2"
  1030. else
  1031. # Debian/Ubuntu
  1032. PHP_INI="/etc/php/$PHP_VERSION/apache2/php.ini"
  1033. APACHE_CONF_DIR="/etc/apache2"
  1034. APACHE_SITES_DIR="$APACHE_CONF_DIR/sites-available"
  1035. DEFAULT_CONF="$APACHE_SITES_DIR/000-default.conf"
  1036. APACHE_USER="www-data"
  1037. fi
  1038. # Configure Apache
  1039. if [[ -f "/opt/Eye/docs/apache/000-default.conf" ]]; then
  1040. print_info "Using prepared Apache template for ALT Linux"
  1041. # Create directory if it doesn't exist
  1042. mkdir -p "$APACHE_SITES_DIR"
  1043. # Copy prepared config
  1044. cp "/opt/Eye/docs/apache/000-default.conf" "$DEFAULT_CONF"
  1045. # Enable site
  1046. if [[ -f "$APACHE_CONF_DIR/sites-enabled/000-default.conf" ]]; then
  1047. rm -f "$APACHE_CONF_DIR/sites-enabled/000-default.conf"
  1048. ln -sf "$DEFAULT_CONF" "$APACHE_CONF_DIR/sites-enabled/000-default.conf"
  1049. fi
  1050. fi
  1051. # Configure sudoers
  1052. if [[ -f "/opt/Eye/docs/sudoers.d/www-data" ]]; then
  1053. # Use prepared template, substituting correct user
  1054. sed "s/www-data/eye/g" /opt/Eye/docs/sudoers.d/www-data > /etc/sudoers.d/eye
  1055. chmod 440 /etc/sudoers.d/eye
  1056. print_info "Sudoers file created from template"
  1057. fi
  1058. # Restart Apache
  1059. if [[ "$OS_FAMILY" == "alt" ]]; then
  1060. # ALT Linux uses httpd2
  1061. APACHE_SERVICE="httpd2"
  1062. else
  1063. APACHE_SERVICE="apache2"
  1064. fi
  1065. # usermod -a -G eye $APACHE_USER
  1066. if [[ "$OS_FAMILY" == "debian" ]]; then
  1067. a2dismod php${PHP_VERSION} 2>/dev/null
  1068. a2dismod mpm_prefork 2>/dev/null
  1069. a2enmod mpm_event 2>/dev/null
  1070. a2enconf php${PHP_VERSION}-fpm 2>/dev/null
  1071. fi
  1072. mkdir -p /var/log/php-fpm/
  1073. a2enmod setenvif
  1074. a2enmod proxy
  1075. a2enmod proxy_fcgi
  1076. print_info "Apache configured, sudoers user: $APACHE_USER"
  1077. print_info "Apache service: $APACHE_SERVICE"
  1078. # Configure php-fpm
  1079. print_info "Configure php-fpm${PHP_VERSION}"
  1080. if [[ -f "/opt/Eye/docs/php-fpm/eye.conf" ]]; then
  1081. print_info "Using prepared php-fpm template"
  1082. if [[ "$OS_FAMILY" == "alt" ]]; then
  1083. cp "/opt/Eye/docs/php-fpm/eye.conf" /etc/fpm${PHP_VERSION}/php-fpm.d/
  1084. else
  1085. cp "/opt/Eye/docs/php-fpm/eye.conf" /etc/php/${PHP_VERSION}/fpm/pool.available/
  1086. ln -sf "/etc/php/${PHP_VERSION}/fpm/pool.available/eye.conf" "/etc/php/${PHP_VERSION}/fpm/pool.d/eye.conf"
  1087. fi
  1088. fi
  1089. $SERVICE_MANAGER enable "$APACHE_SERVICE"
  1090. $SERVICE_MANAGER restart "$APACHE_SERVICE"
  1091. $SERVICE_MANAGER enable php${PHP_VERSION}-fpm.service
  1092. $SERVICE_MANAGER restart php${PHP_VERSION}-fpm.service
  1093. # Check configuration
  1094. if [[ "$OS_FAMILY" == "alt" ]]; then
  1095. httpd2 -t 2>/dev/null && print_info "Apache (httpd2) configuration is valid" || print_warn "Check Apache configuration"
  1096. else
  1097. apache2ctl -t 2>/dev/null && print_info "Apache configuration is valid" || print_warn "Check Apache configuration"
  1098. fi
  1099. }
  1100. # Configure cron and logrotate
  1101. setup_cron_logrotate() {
  1102. print_step "Configuring cron and logrotate"
  1103. # Cron
  1104. if [[ -f "/opt/Eye/docs/cron/stat" ]]; then
  1105. cp /opt/Eye/docs/cron/stat /etc/cron.d/eye
  1106. chmod 644 /etc/cron.d/eye
  1107. print_info "Cron job added: /etc/cron.d/eye"
  1108. fi
  1109. # Logrotate
  1110. if [ -f /etc/dnsmasq.conf ] && [ -f "/opt/Eye/docs/logrotate/dnsmasq" ]; then
  1111. cp /opt/Eye/docs/logrotate/dnsmasq /etc/logrotate.d/dnsmasq-eye
  1112. fi
  1113. if [ -e /opt/Eye/scripts ] && [ -f "/opt/Eye/docs/logrotate/scripts" ]; then
  1114. cp /opt/Eye/docs/logrotate/scripts /etc/logrotate.d/eye-scripts
  1115. fi
  1116. print_info "Cron and logrotate configuration completed"
  1117. print_warn "Edit /etc/cron.d/eye to enable required scripts"
  1118. }
  1119. # Configure DHCP server (dnsmasq)
  1120. setup_dhcp_server() {
  1121. print_step "Configuring DHCP server"
  1122. read -p "Configure DHCP server (dnsmasq)? (y/n): " -n 1 -r
  1123. echo
  1124. if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  1125. return 0
  1126. fi
  1127. if [[ "$OS_FAMILY" == "debian" ]]; then
  1128. apt install dnsmasq -y
  1129. else
  1130. apt-get install dnsmasq -y
  1131. fi
  1132. # Backup configuration
  1133. if [[ -f "/etc/dnsmasq.conf" ]]; then
  1134. cp /etc/dnsmasq.conf /etc/dnsmasq.conf.backup
  1135. fi
  1136. # Copy configuration from Eye
  1137. if [[ -f "/opt/Eye/docs/addons/dnsmasq.conf" ]]; then
  1138. cat /opt/Eye/docs/addons/dnsmasq.conf > /etc/dnsmasq.conf
  1139. fi
  1140. # Copy systemd services
  1141. if [[ -f "/opt/Eye/docs/systemd/dhcp-log.service" ]]; then
  1142. cp /opt/Eye/docs/systemd/dhcp-log.service /etc/systemd/system/
  1143. mkdir -p /etc/systemd/system/dnsmasq.service.d
  1144. cp -f /opt/Eye/docs/systemd/dnsmasq.service.d/override.conf /etc/systemd/system/dnsmasq.service.d
  1145. fi
  1146. if [[ -f "/opt/Eye/docs/systemd/dhcp-log-truncate.service" ]]; then
  1147. cp /opt/Eye/docs/systemd/dhcp-log-truncate.service /etc/systemd/system/
  1148. fi
  1149. # Enable services
  1150. $SERVICE_MANAGER enable dnsmasq
  1151. # $SERVICE_MANAGER start dnsmasq
  1152. print_info "DHCP server configured"
  1153. print_warn "Edit /etc/dnsmasq.conf for your network"
  1154. }
  1155. # Configure syslog-ng
  1156. setup_syslog() {
  1157. print_step "Configuring syslog-ng"
  1158. read -p "Configure remote log collection (syslog-ng)? (y/n): " -n 1 -r
  1159. echo
  1160. if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  1161. return 0
  1162. fi
  1163. if [[ "$OS_FAMILY" == "debian" ]]; then
  1164. apt install syslog-ng -y
  1165. else
  1166. apt-get install syslog-ng syslog-ng-journal -y
  1167. fi
  1168. # Create backup of main config
  1169. if [[ -f "/etc/syslog-ng/syslog-ng.conf" ]]; then
  1170. cp /etc/syslog-ng/syslog-ng.conf /etc/syslog-ng/syslog-ng.conf.backup
  1171. print_info "Backup created: /etc/syslog-ng/syslog-ng.conf.backup"
  1172. fi
  1173. # Copy additional config for Eye
  1174. if [[ -f "/opt/Eye/docs/syslog-ng/eye.conf" ]]; then
  1175. mkdir -p /etc/syslog-ng/conf.d
  1176. cp /opt/Eye/docs/syslog-ng/eye.conf /etc/syslog-ng/conf.d/eye.conf
  1177. # Check if conf.d inclusion already exists in main config
  1178. if [[ -f "/etc/syslog-ng/syslog-ng.conf" ]]; then
  1179. if ! grep -q "@include.*conf\.d" /etc/syslog-ng/syslog-ng.conf && \
  1180. ! grep -q "include.*conf\.d" /etc/syslog-ng/syslog-ng.conf; then
  1181. # Add conf.d directory inclusion to end of file
  1182. echo "" >> /etc/syslog-ng/syslog-ng.conf
  1183. echo "# Include Eye monitoring configuration" >> /etc/syslog-ng/syslog-ng.conf
  1184. echo "@include \"/etc/syslog-ng/conf.d/*.conf\"" >> /etc/syslog-ng/syslog-ng.conf
  1185. print_info "Added conf.d directory inclusion to syslog-ng.conf"
  1186. fi
  1187. fi
  1188. print_info "Configuration file eye.conf copied to /etc/syslog-ng/conf.d/"
  1189. else
  1190. print_warn "eye.conf configuration file not found in /opt/Eye/docs/syslog-ng/"
  1191. fi
  1192. # options block
  1193. syslogng_options='options {
  1194. chain_hostnames(off);
  1195. flush_lines(0);
  1196. use_dns(no);
  1197. use_fqdn(no);
  1198. dns_cache(no);
  1199. owner("root");
  1200. group("adm");
  1201. perm(0640);
  1202. stats_freq(0);
  1203. time_reopen(10);
  1204. log_fifo_size(1000);
  1205. create_dirs(yes);
  1206. keep_hostname(no);
  1207. };'
  1208. # Check for options in main config
  1209. if [[ -f "/etc/syslog-ng/syslog-ng.conf" ]]; then
  1210. if ! grep -q "^options\s*{" /etc/syslog-ng/syslog-ng.conf; then
  1211. # Add options block if it doesn't exist
  1212. if grep -q "^@version:" /etc/syslog-ng/syslog-ng.conf; then
  1213. # Insert after @version: line
  1214. sed -i "/^@version:/a\\$syslogng_options" /etc/syslog-ng/syslog-ng.conf
  1215. else
  1216. # Insert at beginning of file
  1217. sed -i "1i\\$syslogng_options" /etc/syslog-ng/syslog-ng.conf
  1218. fi
  1219. print_info "Added options block to syslog-ng.conf"
  1220. else
  1221. # Check for required parameters in existing options block
  1222. local missing_params=()
  1223. if ! grep -q "time_reopen\s*(.*)" /etc/syslog-ng/syslog-ng.conf; then
  1224. missing_params+=("time_reopen(10)")
  1225. fi
  1226. if ! grep -q "log_fifo_size\s*(.*)" /etc/syslog-ng/syslog-ng.conf; then
  1227. missing_params+=("log_fifo_size(1000)")
  1228. fi
  1229. if ! grep -q "chain_hostnames\s*(.*)" /etc/syslog-ng/syslog-ng.conf; then
  1230. missing_params+=("chain_hostnames(off)")
  1231. fi
  1232. if ! grep -q "create_dirs\s*(.*)" /etc/syslog-ng/syslog-ng.conf; then
  1233. missing_params+=("create_dirs(yes)")
  1234. fi
  1235. if ! grep -q "keep_hostname\s*(.*)" /etc/syslog-ng/syslog-ng.conf; then
  1236. missing_params+=("keep_hostname(no)")
  1237. fi
  1238. # Add missing parameters
  1239. if [[ ${#missing_params[@]} -gt 0 ]]; then
  1240. # Find options block and add parameters to end of block
  1241. sed -i '/^options\s*{/,/^}/ {
  1242. /^}/ i\ '"$(IFS='; '; echo "${missing_params[*]}")"';
  1243. }' /etc/syslog-ng/syslog-ng.conf
  1244. print_info "Added parameters to options block: ${missing_params[*]}"
  1245. fi
  1246. fi
  1247. fi
  1248. # Copy systemd service for Eye log processing
  1249. if [[ -f "/opt/Eye/docs/systemd/syslog-stat.service" ]]; then
  1250. cp /opt/Eye/docs/systemd/syslog-stat.service /etc/systemd/system/
  1251. chmod 644 /etc/systemd/system/syslog-stat.service
  1252. print_info "syslog-stat service copied"
  1253. fi
  1254. # Create log directory if it doesn't exist
  1255. mkdir -p /opt/Eye/scripts/log
  1256. chown eye:eye /opt/Eye/scripts/log
  1257. chmod 770 /opt/Eye/scripts/log
  1258. # Enable and start services
  1259. $SERVICE_MANAGER daemon-reload
  1260. if $SERVICE_MANAGER enable syslog-ng; then
  1261. print_info "syslog-ng service enabled for autostart"
  1262. else
  1263. print_warn "Failed to enable syslog-ng for autostart"
  1264. fi
  1265. if $SERVICE_MANAGER restart syslog-ng; then
  1266. print_info "syslog-ng service restarted"
  1267. else
  1268. print_warn "Failed to restart syslog-ng"
  1269. fi
  1270. if [[ -f "/etc/systemd/system/syslog-stat.service" ]]; then
  1271. if $SERVICE_MANAGER enable syslog-stat; then
  1272. print_info "syslog-stat service enabled for autostart"
  1273. else
  1274. print_warn "Failed to enable syslog-stat for autostart"
  1275. fi
  1276. if $SERVICE_MANAGER start syslog-stat; then
  1277. print_info "syslog-stat service started"
  1278. else
  1279. print_warn "Failed to start syslog-stat"
  1280. fi
  1281. fi
  1282. # Check syslog-ng configuration
  1283. if command -v syslog-ng &> /dev/null; then
  1284. if syslog-ng --syntax-only; then
  1285. print_info "syslog-ng configuration is valid"
  1286. else
  1287. print_error "Error in syslog-ng configuration"
  1288. print_warn "Check files: /etc/syslog-ng/syslog-ng.conf and /etc/syslog-ng/conf.d/eye.conf"
  1289. fi
  1290. fi
  1291. print_info "syslog-ng configuration completed"
  1292. print_info "To receive logs from devices, configure them to send to IP: $(hostname -f)"
  1293. }
  1294. # Configure additional services
  1295. setup_additional_services() {
  1296. print_step "Configuring additional services"
  1297. # stat-sync service
  1298. if [[ -f "/opt/Eye/docs/systemd/stat-sync.service" ]]; then
  1299. cp /opt/Eye/docs/systemd/stat-sync.service /etc/systemd/system/
  1300. $SERVICE_MANAGER enable stat-sync.service
  1301. print_info "stat-sync service enabled"
  1302. fi
  1303. # eye-statd service (NetFlow)
  1304. if [[ -f "/opt/Eye/docs/systemd/eye-statd.service" ]]; then
  1305. cp /opt/Eye/docs/systemd/eye-statd.service /etc/systemd/system/
  1306. $SERVICE_MANAGER enable eye-statd.service
  1307. print_info "eye-statd service (NetFlow) enabled"
  1308. fi
  1309. # Configure DHCP
  1310. setup_dhcp_server
  1311. # Configure syslog
  1312. setup_syslog
  1313. }
  1314. # Import MAC address database
  1315. import_mac_database() {
  1316. print_step "Importing MAC address database"
  1317. if [[ -f "/opt/Eye/scripts/utils/mac-oids/download-macs.sh" ]]; then
  1318. cd /opt/Eye/scripts/utils/mac-oids/
  1319. # Download MAC database
  1320. print_info "Downloading MAC address database..."
  1321. bash download-macs.sh
  1322. # Update vendors
  1323. if [[ -f "update-mac-vendors.pl" ]]; then
  1324. print_info "Updating vendor information..."
  1325. perl update-mac-vendors.pl
  1326. fi
  1327. cd - >/dev/null
  1328. else
  1329. print_warn "MAC address import scripts not found"
  1330. fi
  1331. }
  1332. # Final instructions
  1333. show_final_instructions() {
  1334. echo ""
  1335. echo -e "${GREEN}===========================================${NC}"
  1336. echo -e "${GREEN} INSTALLATION COMPLETED SUCCESSFULLY! ${NC}"
  1337. echo -e "${GREEN}===========================================${NC}"
  1338. echo ""
  1339. echo "SYSTEM INFORMATION:"
  1340. echo " Distribution: $OS_NAME"
  1341. echo " Version: $OS_VERSION"
  1342. echo " Database: $DB_TYPE"
  1343. echo " Language: $EYE_LANG"
  1344. echo " User: eye"
  1345. echo " Directory: /opt/Eye"
  1346. echo ""
  1347. echo ""
  1348. echo "TO COMPLETE SETUP, EXECUTE:"
  1349. echo ""
  1350. echo "1. Configure database security:"
  1351. if [[ "$DB_TYPE" == "postgresql" ]]; then
  1352. print_info " PostgreSQL: Edit pg_hba.conf if needed"
  1353. if [[ -f "/root/eye_postgres_password.txt" ]]; then
  1354. echo ""
  1355. echo "3. PostgreSQL 'stat' user password saved in:"
  1356. echo " /root/eye_postgres_password.txt"
  1357. echo ""
  1358. fi
  1359. else
  1360. echo " mysql_secure_installation"
  1361. if [[ -f "/root/eye_mysql_password.txt" ]]; then
  1362. echo ""
  1363. echo "3. MySQL 'stat' user password saved in:"
  1364. echo " /root/eye_mysql_password.txt"
  1365. echo ""
  1366. fi
  1367. fi
  1368. echo ""
  1369. echo "2. Check and edit configuration files:"
  1370. echo " /opt/Eye/html/cfg/config.php"
  1371. echo " /opt/Eye/scripts/cfg/config"
  1372. echo ""
  1373. echo "4. Configure cron jobs:"
  1374. echo " nano /etc/cron.d/eye"
  1375. echo " Uncomment required scripts"
  1376. echo ""
  1377. echo "5. Configure if necessary:"
  1378. echo " - DHCP: /etc/dnsmasq.conf"
  1379. echo " - NetFlow: configure on network devices"
  1380. echo ""
  1381. echo "6. WEB INTERFACE ACCESS:"
  1382. echo " URL: http://$(hostname -f)/"
  1383. echo " Admin: http://$(hostname -f)/admin/"
  1384. echo " Login: admin"
  1385. echo " Password: admin"
  1386. echo ""
  1387. echo -e "${RED}IMPORTANT:${NC}"
  1388. echo " - CHANGE admin password and API key!"
  1389. echo " - Configure users and networks in web interface"
  1390. echo ""
  1391. echo -e "${GREEN}===========================================${NC}"
  1392. echo ""
  1393. }
  1394. # Final instructions
  1395. show_final_upgrade() {
  1396. echo ""
  1397. echo -e "${GREEN}===========================================${NC}"
  1398. echo -e "${GREEN} UPGRADE COMPLETED SUCCESSFULLY! ${NC}"
  1399. echo -e "${GREEN}===========================================${NC}"
  1400. echo ""
  1401. }
  1402. # Install function
  1403. eye_install() {
  1404. clear
  1405. echo -e "${GREEN}===========================================${NC}"
  1406. echo -e "${GREEN} Installing Eye Monitoring System ${NC}"
  1407. echo -e "${GREEN} for ALT Linux/Debian/Ubuntu ${NC}"
  1408. echo -e "${GREEN}===========================================${NC}"
  1409. echo ""
  1410. # Инициализация глобальных переменных
  1411. DB_PASS=""
  1412. DB_TYPE="mysql"
  1413. EYE_LANG="russian"
  1414. EYE_LANG_SHORT="ru"
  1415. SQL_DATA_FILE=""
  1416. SQL_CREATE_FILE=""
  1417. INSTALL_TYPE="full"
  1418. DB_INSTALL="local"
  1419. # Обязательные шаги (всегда)
  1420. check_root
  1421. detect_distro
  1422. select_language
  1423. # Выбор типа установки (устанавливает INSTALL_TYPE, DB_INSTALL, DB_TYPE и параметры БД)
  1424. select_installation_type
  1425. # Обновление системы и установка пакетов (зависит от типа установки и ОС)
  1426. update_system
  1427. install_packages # ← внутри уже учитывает INSTALL_TYPE и DB_INSTALL
  1428. # Пользователь нужен всегда (для /opt/Eye)
  1429. create_user_group
  1430. # Установка исходного кода (учитывает INSTALL_TYPE)
  1431. install_source_code
  1432. # Настройка БД — ТОЛЬКО если локальная
  1433. if [[ "$DB_INSTALL" == "local" ]]; then
  1434. setup_database
  1435. fi
  1436. # Настройка конфигов — всегда (но внутри учитывает INSTALL_TYPE)
  1437. setup_configs
  1438. # Язык — только если установлен веб
  1439. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "web" ]]; then
  1440. apply_language_settings
  1441. fi
  1442. # Веб-сервер — только если нужен веб
  1443. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "web" ]]; then
  1444. setup_apache_php
  1445. fi
  1446. # Cron и logrotate — только если есть бэкенд (там — фоновые задачи и логи)
  1447. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
  1448. setup_cron_logrotate
  1449. fi
  1450. # Доп. сервисы (dnsmasq, syslog-ng и т.п.) — только для бэкенда
  1451. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
  1452. setup_additional_services
  1453. fi
  1454. # Импорт MAC-базы — только если есть бэкенд (он её использует)
  1455. if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
  1456. import_mac_database
  1457. fi
  1458. show_final_instructions
  1459. }
  1460. backup_current_installation() {
  1461. print_step "Creating full backup of current Eye installation"
  1462. local EYE_ROOT="/opt/Eye"
  1463. local BACKUP_DIR="/opt"
  1464. local TIMESTAMP=$(date +"%Y-%m-%d_%H-%M-%S")
  1465. local BACKUP_FILE="$BACKUP_DIR/eye_backup_${TIMESTAMP}.tar.gz"
  1466. # Проверка: существует ли инсталляция
  1467. if [[ ! -d "$EYE_ROOT" ]]; then
  1468. print_warn "Directory $EYE_ROOT not found — skipping backup"
  1469. return 0
  1470. fi
  1471. # Проверка свободного места (~300 МБ на всякий случай)
  1472. local FREE_SPACE_KB=$(df "$BACKUP_DIR" | awk 'NR==2 {print $4}')
  1473. local MIN_FREE_KB=307200 # ~300 MB
  1474. if [[ $FREE_SPACE_KB -lt $MIN_FREE_KB ]]; then
  1475. print_error "Not enough free space in $BACKUP_DIR for full backup (need ~300 MB)"
  1476. return 1
  1477. fi
  1478. print_info "Creating full backup of $EYE_ROOT (excluding logs and docs)"
  1479. print_info "Backup file: $BACKUP_FILE"
  1480. # Архивируем ВЕСЬ /opt/Eye, но исключаем:
  1481. # - docs/ — не меняется, идёт с дистрибутивом
  1482. # - scripts/log/ — логи (большие, не конфигурация)
  1483. # - html/log/ — если есть
  1484. tar -czf "$BACKUP_FILE" \
  1485. --exclude="docs" \
  1486. --exclude="netflow" \
  1487. --exclude="scripts/log" \
  1488. --exclude="scripts/log/*" \
  1489. --exclude="html/log" \
  1490. --exclude="html/log/*" \
  1491. -C / "opt/Eye" 2>/dev/null
  1492. if [[ $? -eq 0 && -f "$BACKUP_FILE" ]]; then
  1493. print_info "✅ Backup completed successfully"
  1494. chmod 600 "$BACKUP_FILE"
  1495. chown root:root "$BACKUP_FILE"
  1496. else
  1497. print_error "❌ Failed to create backup archive"
  1498. return 1
  1499. fi
  1500. }
  1501. # Upgrade function
  1502. eye_upgrade() {
  1503. clear
  1504. echo -e "${GREEN}===========================================${NC}"
  1505. echo -e "${GREEN} Update Eye Monitoring System ${NC}"
  1506. echo -e "${GREEN}===========================================${NC}"
  1507. echo ""
  1508. check_root
  1509. detect_distro
  1510. stop_eye
  1511. backup_current_installation || {
  1512. echo "CRITICAL: Backup failed. Aborting upgrade."
  1513. start_eye
  1514. exit 1
  1515. }
  1516. update_system
  1517. install_packages
  1518. install_source_code
  1519. import_mac_database
  1520. /opt/Eye/scripts/updates/upgrade.pl
  1521. start_eye
  1522. show_final_upgrade
  1523. }
  1524. # Function to display help
  1525. show_help() {
  1526. echo "Usage: $0 [options]"
  1527. echo ""
  1528. echo "Options:"
  1529. echo " --help, -h Show this help"
  1530. echo " --upgrade, -u Automatic upgrade"
  1531. echo " --install, -i Interactive install"
  1532. echo ""
  1533. echo "Supported distributions:"
  1534. echo " - ALT Linux 11.1+"
  1535. echo " - Debian 11+"
  1536. echo " - Ubuntu 20.04+"
  1537. echo ""
  1538. }
  1539. # Function to check user existence
  1540. check_user() {
  1541. id "eye" &>/dev/null
  1542. return $?
  1543. }
  1544. # Function to check directory existence
  1545. check_directory() {
  1546. [ -d "/opt/Eye" ]
  1547. return $?
  1548. }
  1549. # Function to check if Eye config files exist
  1550. check_eye_configs() {
  1551. # Веб-конфиг
  1552. if [[ -f "/opt/Eye/html/cfg/config.php" ]]; then
  1553. return 0
  1554. fi
  1555. # Бэкенд-конфиг
  1556. if [[ -f "/opt/Eye/scripts/cfg/config" ]]; then
  1557. return 0
  1558. fi
  1559. return 1
  1560. }
  1561. # Handle command line arguments
  1562. case "$1" in
  1563. --help|-h)
  1564. show_help
  1565. exit 0
  1566. ;;
  1567. --upgrade|-u)
  1568. mode="upgrade"
  1569. echo "Mode set to: upgrade"
  1570. ;;
  1571. --install|-i)
  1572. mode="install"
  1573. echo "Mode set to: install"
  1574. ;;
  1575. *)
  1576. # Auto-detect mode
  1577. echo "Auto-detecting installation status..."
  1578. if check_user; then
  1579. user_exists=true
  1580. echo "✓ User 'eye' exists"
  1581. else
  1582. user_exists=false
  1583. echo "✗ User 'eye' does not exist"
  1584. fi
  1585. if check_directory; then
  1586. dir_exists=true
  1587. echo "✓ Directory /opt/Eye exists"
  1588. else
  1589. dir_exists=false
  1590. echo "✗ Directory /opt/Eye does not exist"
  1591. fi
  1592. # Проверяем наличие хотя бы одного конфига Eye
  1593. eye_config_found=false
  1594. if [[ -f "/opt/Eye/html/cfg/config.php" ]] || [[ -f "/opt/Eye/scripts/cfg/config" ]]; then
  1595. eye_config_found=true
  1596. echo "✓ Eye configuration detected"
  1597. fi
  1598. if $user_exists && $dir_exists && $eye_config_found; then
  1599. mode="upgrade"
  1600. echo "Existing Eye installation detected. Switching to upgrade mode."
  1601. # === Восстанавливаем INSTALL_TYPE ===
  1602. if [[ -f "/opt/Eye/html/cfg/config.php" ]] && [[ -f "/opt/Eye/scripts/cfg/config" ]]; then
  1603. INSTALL_TYPE="full"
  1604. elif [[ -f "/opt/Eye/html/cfg/config.php" ]]; then
  1605. INSTALL_TYPE="web"
  1606. elif [[ -f "/opt/Eye/scripts/cfg/config" ]]; then
  1607. INSTALL_TYPE="backend"
  1608. else
  1609. INSTALL_TYPE="full" # fallback
  1610. fi
  1611. # === Восстанавливаем DB_INSTALL (local/remote) ===
  1612. DB_HOST=""
  1613. if [[ -f "/opt/Eye/html/cfg/config.php" ]]; then
  1614. # Извлекаем DB_HOST из PHP-конфига
  1615. DB_HOST=$(grep -oP 'define\s*\(\s*"DB_HOST"\s*,\s*"\K[^"]+' /opt/Eye/html/cfg/config.php 2>/dev/null)
  1616. fi
  1617. if [[ -z "$DB_HOST" && -f "/opt/Eye/scripts/cfg/config" ]]; then
  1618. # Извлекаем из Perl-конфига
  1619. DB_HOST=$(grep -oP '^DBHOST=\K.*' /opt/Eye/scripts/cfg/config 2>/dev/null)
  1620. fi
  1621. if [[ "$DB_HOST" == "127.0.0.1" || "$DB_HOST" == "localhost" || "$DB_HOST" == "::1" ]]; then
  1622. DB_INSTALL="local"
  1623. else
  1624. DB_INSTALL="remote"
  1625. fi
  1626. # === Восстанавливаем DB_TYPE ===
  1627. if [[ -f "/opt/Eye/html/cfg/config.php" ]]; then
  1628. DB_TYPE=$(grep -oP 'define\s*\(\s*"DB_TYPE"\s*,\s*"\K[^"]+' /opt/Eye/html/cfg/config.php 2>/dev/null)
  1629. # В PHP может быть 'pgsql' вместо 'postgresql'
  1630. if [[ "$DB_TYPE" == "pgsql" ]]; then
  1631. DB_TYPE="postgresql"
  1632. elif [[ "$DB_TYPE" == "mysql" ]]; then
  1633. DB_TYPE="mysql"
  1634. fi
  1635. elif [[ -f "/opt/Eye/scripts/cfg/config" ]]; then
  1636. DB_TYPE=$(grep -oP '^DBTYPE=\K.*' /opt/Eye/scripts/cfg/config 2>/dev/null)
  1637. fi
  1638. # Защита от неопределённых значений
  1639. : "${INSTALL_TYPE:=full}"
  1640. : "${DB_INSTALL:=remote}"
  1641. : "${DB_TYPE:=mysql}"
  1642. echo " → INSTALL_TYPE = $INSTALL_TYPE"
  1643. echo " → DB_INSTALL = $DB_INSTALL"
  1644. echo " → DB_TYPE = $DB_TYPE"
  1645. else
  1646. mode="install"
  1647. echo "No existing Eye installation found. Switching to install mode."
  1648. fi
  1649. ;;
  1650. esac
  1651. echo ""
  1652. echo "Selected mode: $mode"
  1653. # Main execution based on mode
  1654. case "$mode" in
  1655. "upgrade")
  1656. echo "Starting upgrade process..."
  1657. # Start upgrade
  1658. eye_upgrade
  1659. ;;
  1660. "install")
  1661. echo "Starting installation process..."
  1662. # Start installation
  1663. eye_install
  1664. ;;
  1665. *)
  1666. echo "Error: Unknown mode '$mode'"
  1667. exit 1
  1668. ;;
  1669. esac
  1670. # Exit with success code
  1671. exit 0