install-eye.sh 67 KB

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