#!/bin/bash

# Цвета для вывода
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

REPO_TYPE=${1:-stable}  # Тип репозитория, необходимо заменить на stable или testing, заменяется в job-е Jenkins-а
UPDATE=${2:-false} # true - обновление, false - установка (отличаются тем, что при обновлении не добавляются репозитории)
SCRIPTS_URL=https://update.artix.su/static/cs/install_scripts/${REPO_TYPE}/cs_env

if [[ ${UPDATE} == false ]]; then
  
  mongo --eval "db.stats()" >> /dev/null 2>&1
  RESULT=$?
  apt install wget -y
  case ${REPO_TYPE} in
      stable)
       echo -e "${GREEN}Добавление stable-репозитория...${NC}"
       wget -O - https://update.artix.su/artix.gpg.key | gpg --dearmor > /etc/apt/trusted.gpg.d/artix.gpg -
       echo 'deb [arch=amd64] https://update.artix.su/lm/ loyalty_testing loyalty' | sudo tee /etc/apt/sources.list.d/loyalty.list
       ;;
      prerelease | testing)
       echo -e "${GREEN}Добавление testing-репозитория...${NC}"
       wget -O - https://update.artix.su/artix.gpg.key | gpg --dearmor > /etc/apt/trusted.gpg.d/artix.gpg -
       echo 'deb [arch=amd64] https://update.artix.su/cs/ cashserver3_testing cashserver3' | sudo tee /etc/apt/sources.list.d/loyalty.list
       ;;
      *)
       echo -e ${RED}Неизвестный тип репозитория: ${REPO_TYPE}${NC}
       exit 1
  esac

  if [[ ${RESULT} == 127 ]]; then
    echo -e "${GREEN}MongoDB не установлена, скачиваем установочный скрипт...${NC}"
    curl ${SCRIPTS_URL}/add_rep.sh -o /tmp/add_rep_cs.sh
    chmod +x /tmp/add_rep_cs.sh
    /tmp/add_rep_cs.sh ${REPO_TYPE}

    repo_codename=$(lsb_release -sc)
    echo -e "${GREEN}Обнаружен дистрибутив: ${repo_codename}${NC}"

    apt update
    if  grep -qs 'avx\b' /proc/cpuinfo; then
      apt install -y mongodb-org mongodb-org-database
    else
      apt-get install -y mongodb-org=4.4.30 mongodb-org-database-tools-extra=4.4.30 mongodb-org-tools=4.4.30 mongodb-org-mongos=4.4.30 mongodb-org-server=4.4.30 mongodb-org-shell=4.4.30
    fi
  fi  
fi

echo -e "${GREEN}Установка artixcs-telegram-bot...${NC}"
sudo apt update
sudo apt install artixcs-telegram-bot

# для ubuntu 18 необходимо добавление mongod в автозапуск
if [[ ${RESULT} == 127 ]] && type systemctl > /dev/null 2>&1; then
    echo -e "${GREEN}Добавление mongod в автозагрузку...${NC}"
    systemctl enable mongod
    systemctl restart mongod
fi
