install-eye.sh 71 KB

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