install-eye.sh 70 KB

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