#!/bin/bash

registry="premise-registry.mts-link.net"
license="license-chat.mts-link.ru"
environment="09_25"

if [ -f /opt/weteams/license.txt ]; then
  export MODE=UPDATE
else
  export MODE=INSTALL
fi

. /etc/os-release

if [[ $ID == debian ]]; then
  export PM="apt"
elif [[ $ID == redos ]]; then
  export PM="dnf"
else
  echo "Not support $ID system" >&2
  exit 1
fi

if [ "$MODE" = "INSTALL" ]; then
  if [ -f /opt/weteams ]; then
    $PM update
    $PM install -y curl wget jq
  fi

  status_code=$(curl --write-out %{http_code} --silent --output /dev/null https://$license)
  if [[ "$status_code" -ne 404 ]] ; then
    echo "can't connect to license server"
    exit 1
  fi
  
  status_check_id=$(grep 'tape:x:33:' -c /etc/group)
  if [[ "$status_check_id" -ne 0 ]]; then
    groupmod -g 34 tape
    useradd -u 33 -r -s /usr/sbin/nologin www-data
  fi
fi

case "$1" in
  --cfglink)
    read -p "Enter chats domain name: " main_domain
    first_word=$(echo $main_domain | cut -d '.' -f 1)
    domain_without_subdomain=$(echo $main_domain | cut -d '.' -f 2-)
    chatgatedom=$first_word-gateway.$domain_without_subdomain
    kafka_url="https://$chatgatedom/onprem/api/OnpremHttp.PublicEvent"
    env_file="/opt/webinar/web/volume/api/.env"
    conf_js_file='/opt/webinar/web/volume/frontend/configs/config.js'
    sed -i -e 's/SERVICE_HTTP_TO_KAFKA_ENABLED=False$/SERVICE_HTTP_TO_KAFKA_ENABLED=true/g' $env_file
    sed -i -e 's%SERVICE_HTTP_TO_KAFKA_URL=$%SERVICE_HTTP_TO_KAFKA_URL='$kafka_url'%g' $env_file
    sed -i -e 's%SERVICE_HTTP_TO_KAFKA_TOKEN=$%SERVICE_HTTP_TO_KAFKA_TOKEN=6k6qbwdCrgEksS4Y8RwT5E2aoZ9HISiePmD%g' $env_file
    sed -i -e 's%LINK_CHATS_API_DOMAIN=$%LINK_CHATS_API_DOMAIN=https://'$main_domain'%g' $env_file
    sed -i -e 's%LINK_CHATS_API_BASE_URL=$%LINK_CHATS_API_BASE_URL=https://'$chatgatedom'/chats/backoffice/api/Admin.ExecuteRemoteContract%g' $env_file
    sed -i -e 's%LINK_CHATS_ENV_CONFIG_URL=$%LINK_CHATS_ENV_CONFIG_URL=https://'$main_domain'/chats/env-config.js%g' $env_file
    sed -i -e 's%LINK_CHAT_URL=$%LINK_CHAT_URL=https://'$main_domain'/application/webhook%g' $env_file
    sed -i -e 's%LINK_CHATS_API_DOMAIN=$%LINK_CHATS_API_DOMAIN=https://'$main_domain'%g' $env_file
    sed -i -e 's/default_chats_domain/'$main_domain'/g' $conf_js_file
    sed -i -e 's/default_chats_gateway_domain/'$chatgatedom'/g' $conf_js_file
    /opt/webinar/scripts/add_feature.sh syncUsersMessenger
    /opt/webinar/scripts/add_feature.sh autoBroadcastingOnCall
    /opt/webinar/scripts/add_feature.sh enterEventLinkChats
    /opt/webinar/scripts/add_feature.sh enterEventLinkOnlyChats
    /opt/webinar/scripts/add_feature.sh userStatusInCallByNewMessageChannel
    /opt/webinar/scripts/add_feature.sh useVirtualConference
    /opt/webinar/scripts/add_feature.sh meetingToChatCall
    contname="web-application-php-cli"
    BASH_VAR=$( { docker exec $contname php /var/www/api/bin/console identity-provider:client:create "Чаты" --uri https://$chatgatedom/Account/oauth/callback --project chat --share; } 2>&1 )
    docker-compose -f /opt/webinar/web/docker-compose.yml down
    docker-compose -f /opt/webinar/web/docker-compose.yml up --always-recreate-deps --remove-orphans -d memcache
    docker-compose -f /opt/webinar/web/docker-compose.yml up --always-recreate-deps --remove-orphans -d nginx
    docker-compose -f /opt/webinar/web/docker-compose.yml up --always-recreate-deps --remove-orphans -d php
    docker-compose -f /opt/webinar/web/docker-compose.yml up --always-recreate-deps --remove-orphans -d php-cli
    docker-compose -f /opt/webinar/web/docker-compose.yml up --always-recreate-deps --remove-orphans -d statistics-generator
    docker-compose -f /opt/webinar/web/docker-compose.yml up --always-recreate-deps --remove-orphans -d supervisor
    docker-compose -f /opt/webinar/web/docker-compose.yml up --always-recreate-deps --remove-orphans -d effects-sdk
    client_id=$(echo $BASH_VAR | cut -d ' ' -f10)
    client_secret=$(echo $BASH_VAR | cut -d ' ' -f12)
    echo "Client ID: " $client_id
    echo "Client secret: " $client_secret
  ;;
  *)
    if [ "$MODE" = "INSTALL" ]; then
      if [[ ! -f /usr/bin/docker ]]; then
        if [ $PM = "apt" ]; then
          $PM install -y docker.io python-is-python3 python3-psycopg2 rsync sudo haproxy jq figlet
          if [[ ! -f /usr/local/bin/docker-compose || ! -f /usr/bin/docker-compose ]]; then
            wget -O /usr/local/bin/docker-compose https://rep-box.webinar.ru/contrib/docker-compose-Linux-x86_64
            chmod +x /usr/local/bin/docker-compose
          fi
        else
          $PM install -y docker-ce docker-ce-cli docker-compose python3-docker python3-psycopg2 haproxy jq figlet
          systemctl enable docker haproxy
          systemctl start docker
        fi       
      fi

      figlet mts-link-chats
      
      read -p "Enter license key: " license_key
      read -p "Enter client id: " client_id
      read -p "Enter client secret: " client_secret

      status_code_license=$(curl --write-out %{http_code} --silent --output /dev/null https://$license/signature/{$license_key})
      if [[ "$status_code_license" -ne 200 ]] ; then
        echo "License key not valid"
        exit 1
      fi
    else
      figlet "Start update mts-link-chats"

      license_key=$(grep -w "LICENSE_KEY" /opt/weteams/gateway/.env | cut -d '=' -f2 | tr -d '"')
      client_id=$(grep -w "OAUTH_CLIENTID" /opt/weteams/account-api-go/.env | cut -d '=' -f2 | tr -d '"')
      client_secret=$(grep -w "OAUTH_CLIENTSECRET" /opt/weteams/account-api-go/.env | cut -d '=' -f2)
    fi

    domain_signature=$(curl -s https://$license/signature/{$license_key})
    lic_data=$(curl -s https://$license/params/$license_key)
    main_domain=$(echo $lic_data | jq -r ".domain_chats")
    link_domain=$(echo $lic_data | jq -r ".domain_webinars")
    registry=$(echo $lic_data | jq -r ".domain_registry")
    user=$(echo $lic_data | jq -r ".registry_login")
    password=$(echo $lic_data | jq -r ".registry_password")
    installation_name=$(echo $lic_data | jq -r '.installation_name')
    first_word=$(echo $main_domain | cut -d '.' -f 1)
    domain_without_subdomain=$(echo $main_domain | cut -d '.' -f 2-)
    domain_gateway=$first_word-gateway.$domain_without_subdomain
    domain_storage=$first_word-storage.$domain_without_subdomain
    domain_s3=$first_word-s3.$domain_without_subdomain
    cors_domain=$domain_without_subdomain
    short_domain=$first_word-gateway
    main_ip=$(getent ahostsv4 $main_domain | cut -d ' ' -f1 | sort -u)

    string=$(docker login --username $user --password $password https://$registry)
    if [[ $string != *"Login Succeeded"* ]]; then
      echo "Incorrect login or password"
      exit 1
    fi

    if [ "$MODE" = "INSTALL" ]; then
      status_code_registry=$(curl --write-out %{http_code} --silent --output /dev/null https://$registry/login/auth)
      if [[ "$status_code_registry" -ne 200 ]] ; then
        echo "Can't connect to repository" 
        exit 1
      fi
      if [[ ! -f certs/$main_domain.crt ]] ; then
        echo 'File "certs/'$main_domain'.crt" is not there, aborting.'
        exit 1
      fi
      if [[ ! -f certs/$main_domain.key ]] ; then
        echo 'File "certs/'$main_domain'.key" is not there, aborting.'
        exit 1
      fi

      check_ssl_crt=$(openssl x509 -noout -modulus -in certs/$main_domain.crt | openssl md5)
      check_ssl_key=$(openssl rsa -noout -modulus -in certs/$main_domain.key | openssl md5)
      check_ssl_exp=$(openssl x509 -noout -enddate -in certs/$main_domain.crt | cut -c10- | date +%s -f -)

      if [[ $(date +%s) -ge $check_ssl_exp ]]; then
        echo "Certificate expired"
        exit 1
      fi
      if [[ "$check_ssl_crt" != "$check_ssl_key"  ]]; then
        echo "Certificate not a valid"
        exit 1
      else
        echo "Certificate $main_domain is valid"
      fi
      if [[ ! -d /etc/pki ]]; then
        mkdir /etc/pki
      fi

      cp certs/$main_domain.crt /etc/pki/$cors_domain.crt
      cp certs/$main_domain.key /etc/pki/$cors_domain.key
      cp license.txt roles/common/templates/license.txt
    fi

    wget -q https://rep-box.webinar.ru/$environment/chats/chats.tar.gz
    tar xzf chats.tar.gz
    rm -fr chats.tar.gz

    sed -i -e "s/default_domain/$main_domain/g" group_vars/all/all.yml
    sed -i -e "s/default_gateway_domain/$domain_gateway/g" group_vars/all/all.yml
    sed -i -e "s/default_storage_domain/$domain_storage/g" group_vars/all/all.yml
    sed -i -e "s/default_s3_domain/$domain_s3/g" group_vars/all/all.yml
    sed -i -e "s/default_signature_domain/$domain_signature/g" group_vars/all/all.yml
    sed -i -e "s/default_license_key/$license_key/g" group_vars/all/all.yml
    sed -i -e "s/default_link_domain/$link_domain/g" group_vars/all/all.yml
    sed -i -e "s/default_short_domain/$short_domain/g" group_vars/all/all.yml
    sed -i -e "s/default_cors_domain/$cors_domain/g" group_vars/all/all.yml
    sed -i -e "s/default_license_url/$license/g" group_vars/all/all.yml
    sed -i -e "s/default_registry_url/$registry/g" group_vars/all/all.yml
    sed -i -e "s/default_installation_name/$installation_name/g" group_vars/all/all.yml
    sed -i -e "s/default_main_ip/$main_ip/g" group_vars/all/all.yml
    sed -i -e "s/default_docker_login/$user/g" group_vars/all/all.yml
    sed -i -e "s/default_docker_password/$password/g" group_vars/all/all.yml
    sed -i -e "s/default_client_id/$client_id/g" group_vars/all/all.yml
    sed -i -e "s/default_client_secret/$client_secret/g" group_vars/all/all.yml

    useradd -m -s /bin/bash ansinst
    echo "ansinst ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/99-ansible-inst-user
    mkdir -p /home/ansinst/.ssh
    echo 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIK9bCtOQgUcDHteFr7PBcnN8F37+9Ag9iBgOZEz5mJyd' > /home/ansinst/.ssh/authorized_keys

    ans_port=$(grep -w "Port" /etc/ssh/sshd_config | awk '{print $2}' | head -n 1)
    sed -i -e "s/default_domain/$main_domain/g" inventory
    sed -i -e "s/default_ip/$main_ip/g" inventory
    sed -i -e "s/default_port/$ans_port/" inventory

    if [ "$MODE" = "UPDATE" ]; then
      ans_extra_args="-t update"
    else
      ans_extra_args=""
    fi
    
    spin='-\|/'
    docker run --rm --name ansible -v $(pwd):/playbook/ $registry/messenger/ansible ansible-playbook -i inventory first_init.yml $ans_extra_args >> install.log 2>&1 &
    pid=$! # PID Process

    i=0
    while kill -0 $pid 2>/dev/null; do
      i=$(( (i+1) % 4 ))
      printf "\r${spin:$i:1} Performing operations ..."
      sleep 0.1
    done

    wait $pid

    if [[ $(tail -n11 install.log | grep -c failed=0) -eq 1 ]]; then
      if [ "$MODE" = "INSTALL" ]; then
        INT_ID=$( { docker exec admin-api ./cli create-link-app-token; } 2>&1 )
        echo -e "\nYour integrational token: $INT_ID"
        echo -e "\nInstallation complete"
      else
        echo -e "\nUpdate complete"
      fi
    else
      if [ "$MODE" = "INSTALL" ]; then
        echo -e "\nInstallation failed! Check install.log and fix error!"
      else
        echo -e "\nUpdate failed! Check install.log and fix error!"
      fi
    fi

    docker image rm $registry/messenger/ansible >> install.log 2>&1
    userdel -f -r ansinst >> install.log 2>&1
    rm -rf /home/ansinst >> install.log 2>&1
    rm /etc/sudoers.d/99-ansible-inst-user >> install.log 2>&1
    rm first_init.yml
    rm inventory
    rm -rf group_vars
    rm -rf roles
  ;;
esac
