install-eye.sh 65 KB

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