install-eye.sh 67 KB

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