install-eye.sh 66 KB

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