#!/bin/bash

registry="premise-registry.mts-link.net"
environment="08_25"

. /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

$PM install -y curl

status_code=$(curl --write-out %{http_code} --silent --output /dev/null https://$registry/login/auth)
if [[ "$status_code" -ne 200 ]] ; then
  echo "can't connect to repository" 
  exit 1
fi
status_code=$(curl --write-out %{http_code} --silent --output /dev/null https://rep-box.webinar.ru/$environment/webinar/mts-link-installer.sh)
if [[ "$status_code" -ne 200 ]] ; then
  echo "can't connect to repository"
  exit 1
fi

function rm_src {
    rm -rf core/
    rm -rf media-msg/
    rm -rf webinar-media/
    rm -rf mts-link-web-test/
    rm -rf webinar-v3-db/
    rm -rf transcribe/
    rm -rf sip/
    rm -rf vars/
}

function install_docker {
  if [[ ! -f /usr/bin/docker ]]; then
    if [ $ID = "debian" ]; then
      $PM install -y docker.io python3-docker python-is-python3
      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
      systemctl enable docker
      systemctl restart docker
    fi       
  fi
}

function stage_runner() {
  echo "start_$1"
  echo "start_$1" >> install.log
  local spin='-\|/'
  local i=0
  sleep 3

  ansible-playbook $2 $ans_extra_args $3 >> install.log 2>&1 &
  local pid=$!
  while kill -0 $pid 2>/dev/null; do
    i=$(( (i+1) %4 ))
    printf "\r${spin:$i:1}"
    sleep .1
  done
  
  echo "end_$1" >> install.log
  if [[ $(tail -n3 install.log | grep -c failed=0) -eq 1 ]]; then
    echo "$1 complete"
    return 0
  else
    echo "Stopped $1! Installation aborted! Check install.log and fix error!"
    rm_src 
    exit 1
  fi
}

function certificate_check() {
  if [[ ! -f certs/$1.crt ]] ; then
    echo 'File "certs/'$1'.crt" is not there, aborting.'
    exit 1
  fi
  if [[ ! -f certs/$1.crt ]] ; then
    echo 'File "certs/'$1'.key" is not there, aborting.'
    exit 1
  fi
}

case "$1" in
  --sip)
    $PM update
    $PM install -y figlet
    install_docker
    figlet mts-link sip

    read -p "Enter sip domain name: " sip_domain
    read -p "Enter main domain name: " domain_main
    read -p "Enter registry user: " user
    read -p "Enter registry password: " password
    read -p "Enter vinteo domain name: " vinteo_domain
    read -p "Enter vinteo user: " vinteo_user
    read -p "Enter vinteo password : " vinteo_password

    main_ip=$(getent ahostsv4 $domain_main | cut -d ' ' -f1 | sort -u)
    if [[ ! -f certs/$sip_domain.crt ]] ; then
      echo 'File "certs/'$sip_domain'.crt" is not there, aborting.'
      exit 1
    fi
    if [[ ! -f certs/$sip_domain.crt ]] ; then
      echo 'File "certs/'$sip_domain'.key" is not there, aborting.'
      exit 1
    fi

    mkdir -p /opt/webinar/cert/
    cp certs/$sip_domain.crt /opt/webinar/cert/
    cp certs/$sip_domain.key /opt/webinar/cert/

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

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

    echo "domain_main: $domain_main" > vars/collect_vars.yml
    echo "domain_sip: $sip_domain" >> vars/collect_vars.yml
    echo "domain_vinteo: $vinteo_domain" >> vars/collect_vars.yml
    echo "ip_sip: $main_ip" >> vars/collect_vars.yml
    echo "docker_user: $user" >> vars/collect_vars.yml
    echo "docker_password: $password" >> vars/collect_vars.yml
    echo "vinteo_user: $vinteo_user" >> vars/collect_vars.yml
    echo "vinteo_password: $vinteo_password" >> vars/collect_vars.yml
    echo "docker_registry: $registry" >> vars/collect_vars.yml
    stage_runner stage_sip sip/first_init.yml
    rm_src
    ;;
  --sipcfg)
    $PM update
    $PM install -y figlet
    figlet mts-link sip
    read -p "Enter sip domain name: " sip_domain
    if [[ -f /opt/webinar/web/volume/api/.env ]]; then
      /opt/webinar/scripts/add_feature.sh useSipCalls
      /opt/webinar/scripts/add_feature.sh useIncomingExolve
      /opt/webinar/scripts/add_feature.sh useIncomingPbx
      sed -i -e "s/SIP_URI_HOST=.*$/SIP_URI_HOST=$sip_domain/g" /opt/webinar/web/volume/api/.env
      sed -i -e "s/WRC_BASE_URL=.*$/WRC_BASE_URL=http\:\/\/$sip_domain:5060/g" /opt/webinar/web/volume/api/.env
      docker-compose --file /opt/webinar/web/docker-compose.yml down
      docker-compose --file /opt/webinar/web/docker-compose.yml up -d
    else
      echo "MTS Link is not install to this server"
    fi
    ;;
  *)
    if [ -f /opt/webinar/license/license.txt ]; then
      export MODE=UPDATE
    else
      export MODE=INSTALL
    fi

    if [ "$MODE" = "INSTALL" ]; then
      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

      status_code=$(curl --write-out %{http_code} --silent --output /dev/null https://on-premise-reg.webinar.ru)
      if [[ "$status_code" -ne 404 ]] ; then
        echo "can't connect to license server"
        exit 1
      fi
      if [[ ! -f license.txt ]] ; then
        echo 'File "license.txt" is not there, aborting.'
        exit 1
      fi

      install_docker
      if [ $ID = "debian" ]; then
        $PM install -y ansible rsync python-is-python3 wget jq python3-docker logrotate haproxy figlet
      else
        $PM install -y ansible rsync python3-docker wget jq logrotate haproxy figlet  
      fi

      figlet "mts-link"
    else
      figlet "start update mts-link"
    fi

    read -p "Enter main domain name: " domain_main
    read -p "Enter user: " user
    read -p "Enter password: " password

    if [ "$MODE" = "INSTALL" ]; then
      if [[ ! -f certs/$domain_main.crt ]] ; then
          echo 'File "certs/'$domain_main'.crt" is not there, aborting.'
          exit 1
      fi
      if [[ ! -f certs/$domain_main.key ]] ; then
          echo 'File "certs/'$domain_main'.key" is not there, aborting.'
          exit 1
      fi
    fi

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

    domain_sub=$(echo $domain_main | cut -d '.' -f 1)
    domain_cors=$(echo $domain_main | cut -d '.' -f 2-)
    domain_media=$domain_sub-wowza.$domain_cors
    domain_live=$domain_sub-webrtc.$domain_cors
    domain_mgw=$domain_sub-mgw.$domain_cors
    domain_msg=$domain_sub-message.$domain_cors
    main_ip=$(getent ahostsv4 $domain_main | cut -d ' ' -f1 | sort -u)
    wowza_ip=$(getent ahostsv4 $domain_media | cut -d ' ' -f1 | sort -u)
    webrtc_ip=$(getent ahostsv4 $domain_live | cut -d ' ' -f1 | sort -u)
    mgw_ip=$(getent ahostsv4 $domain_mgw | cut -d ' ' -f1 | sort -u)
    message_ip=$(getent ahostsv4 $domain_msg | cut -d ' ' -f1 | sort -u)
    cors_nginx=${domain_cors//./\\.}
    if [[ $ID == debian ]]; then
      cors_env=${domain_cors//./\\\\\\\\\\\\\\\\.}
    elif [[ $ID == redos ]]; then
      cors_env=$domain_cors
    fi
    read -p "Use NAT y or n ? : " nat
    if [[ $nat = "y" ]]; then
      nat=true
      read -p "Input external ip address: " external_ip
      echo $external_ip
    else
      nat=false
      external_ip=$main_ip
      echo $external_ip
    fi

    if [ "$MODE" = "INSTALL" ]; then
      check_ssl_crt=$(openssl x509 -noout -modulus -in certs/$domain_main.crt | openssl md5)
      check_ssl_key=$(openssl rsa -noout -modulus -in certs/$domain_main.key | openssl md5)
      check_ssl_exp=$(openssl x509 -noout -enddate -in certs/$domain_main.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 $domain_main is valid"
      fi
      echo >> certs/$domain_main.crt
    fi

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

    group_vars="mts-link-web-test/environments/premise/group_vars/web/main.yml"
    if [ "$MODE" = "INSTALL" ]; then
      cp license.txt mts-link-web-test/environments/premise/license.txt.j2
      mkdir -p core/roles/folders/tasks/files/
      cp certs/$domain_main.crt core/roles/folders/tasks/files/
      cp certs/$domain_main.key core/roles/folders/tasks/files/
    else
      MYSQL_CONT=$(docker ps -a --format '{{.Names}}' | grep mysql)
      MYSQLPASS=$(docker inspect $MYSQL_CONT | awk -F = '/MYSQL_ROOT_PASSWORD/ {print $2}')
      chats=$(docker exec $MYSQL_CONT mysql -p"${MYSQLPASS::-2}" api_v2 -e 'select redirectUri from IdpOAuthClient where project = "chat"' 2>&1 | awk -F "/" '/gateway/ {print $3}' | sed 's/-gateway\./\./')
      if [[ $chats ]]; then
        chats_on=true
        first_word_chat=$(echo $chats | cut -d '.' -f 1)
        domain_without_subdomain_chat=$(echo $chats | cut -d '.' -f 2-)
        chatgatedom=$first_word_chat-gateway.$domain_without_subdomain_chat
        sed -i -e "s/SERVICE_HTTP_TO_KAFKA_ENABLED=false/SERVICE_HTTP_TO_KAFKA_ENABLED=$chats_on/g" $group_vars
        sed -i -e "s/default_chats_domain/$chats/g" $group_vars
        sed -i -e "s/default_chats_gateway_domain/$chatgatedom/g" $group_vars
      fi
      sip_domain=$(grep SIP_URI_HOST /opt/webinar/web/volume/api/.env | cut -d '=' -f2 | cut -c 2-)
      if [[ $sip_domain != "sip.domain.com" ]]; then
        sed -i -e "s/sip.domain.com/$sip_domain/g" $group_vars
      fi
      MYSQL_CONT=$(docker ps -a --format '{{.Names}}' | grep mysql)
      MYSQLPASS=$(docker inspect $MYSQL_CONT | awk -F = '/MYSQL_ROOT_PASSWORD/ {print $2}')
      boards=$(docker exec $MYSQL_CONT mysql -p"${MYSQLPASS::-2}" api_v2 -e 'select redirectUri from IdpOAuthClient where project = "boards"' 2>&1 | awk -F "/" '/boards/ {print $3}')
      if [[ $boards ]]; then
        sed -i -e "s/default_boards_domain/$boards/g" $group_vars
      fi
    fi

    echo "domain_main: $domain_main" > vars/collect_vars.yml
    echo "domain_media: $domain_media" >> vars/collect_vars.yml
    echo "domain_mgw: $domain_mgw" >> vars/collect_vars.yml
    echo "domain_live: $domain_live" >> vars/collect_vars.yml
    echo "domain_msg: $domain_msg" >> vars/collect_vars.yml
    echo "domain_sub: $domain_sub" >> vars/collect_vars.yml
    echo "domain_cors: $domain_cors" >> vars/collect_vars.yml
    echo "ip_address: $main_ip" >> vars/collect_vars.yml
    echo "external_ip: $external_ip" >> vars/collect_vars.yml
    echo "rabbitmq_host: $domain_main" >> vars/collect_vars.yml
    echo "nat: $nat" >> vars/collect_vars.yml
    echo "docker_registry: $registry" >> vars/collect_vars.yml
    echo "docker_user: $user" >> vars/collect_vars.yml
    echo "docker_password: $password" >> vars/collect_vars.yml
    echo "cors_nginx: $cors_nginx" >> vars/collect_vars.yml
    echo "cors_env: $cors_env" >> vars/collect_vars.yml

    sed -i -e "s/default_domain_name/$domain_main/g" $group_vars
    sed -i -e "s/default_cors_env/$cors_env/g" $group_vars
    sed -i -e "s/default_domain_cors/$domain_cors/g" $group_vars
    sed -i -e "s/default_domain_live/$domain_live/g" $group_vars
    sed -i -e "s/default_domain_media/$domain_media/g" $group_vars
    sed -i -e "s/default_first_word-main/$domain_sub/g" $group_vars
    sed -i -e "s/default_first_word-message/$domain_sub-message/g" $group_vars
    sed -i -e "s/default_first_word-mgw/$domain_sub-mgw/g" $group_vars
    sed -i -e "s/default_first_word-webrtc/$domain_sub-webrtc/g" $group_vars
    sed -i -e "s/default_first_word-wowza/$domain_sub-wowza/g" $group_vars
    sed -i -e "s/smtp..webinar.ru/smtp.domain.name/g" mts-link-web-test/environments/premise/.env.j2
    sed -i -e "/37.130.192.0/d" mts-link-web-test/environments/premise/parameters.yml.j2
    sed -i -e "/185.45.80.0/d" mts-link-web-test/environments/premise/parameters.yml.j2
    sed -i -e "s/public_ip_list:/public_ip_list: ''/g" mts-link-web-test/environments/premise/parameters.yml.j2
    if [[ $ID == redos ]]; then
        sed -i -e "s%\\\\%%g" $group_vars
    fi

    if [ "$MODE" = "UPDATE" ]; then
      ans_extra_args='--tags update,untagged'
    else
      ans_extra_args='--tags install,untagged'
    fi
    
    stage_runner stage_0 core/core.yml
    stage_runner stage_1 media-msg/msg.yml
    stage_runner stage_2 webinar-v3-db/db.yml
    stage_runner stage_3 mts-link-web-test/playbook-premise.yml "--inventory-file=mts-link-web-test/environments/premise/inventory"
    stage_runner stage_4 webinar-media/media.yml
    stage_runner stage_5 transcribe/main.yml

    cp version /opt/webinar/version
    rm_src
    echo "Congratulations! The Webinar platform has been successfully installed."
  ;;
esac
