#!/bin/bash

environment="01_26"
license="license-chat.mts-link.ru"

if [ -f /opt/boards/license/box.data ]; 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/boards ]; then
    $PM update
    $PM install -y curl wget jq openssl figlet
  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

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

  docker run --rm --name ansible -v $(pwd):/playbook/ $registry/boards/ansible \
  ansible-playbook -i inventory $2 $ans_extra_args >> install.log 2>&1 &
  local pid=$!
  while kill -0 $pid 2>/dev/null; do
    echo -ne "\r\033[32m${spin[$i]}\033[0m $1 in progress .."
    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 -e "$1 \033[32mcompleted\033[0m operations"
    return 0
  else
    echo -e "Stopped $1! \033[31mOperation aborted\033[0m! Check install.log and fix error!"
    return 1
  fi
}

function rm_src(
  docker image rm $registry/boards/ansible >> install.log 2>&1
  userdel -f -r ansinst >> install.log 2>&1
  rm -rf /home/ansinst >> install.log 2>&1
  rm -f /etc/sudoers.d/99-ansible-inst-user >> install.log 2>&1
  rm -rf group_vars
  rm -rf roles
  rm -f media_temp.tar.gz
  rm -rf first_init.yml
  rm -rf inventory
)

case "$1" in
  --cfglink)
    read -p "Enter boards domain name: " main_domain
    env_file="/opt/webinar/web/volume/api/.env"
    conf_js_file='/opt/webinar/web/volume/frontend/configs/config.js'
    sed -i -e 's%JESPO_BASE_URL=$%JESPO_BASE_URL='$main_domain'%g' $env_file
    sed -i -e 's%default_boards_domain%'$main_domain'%g' $conf_js_file
    contname="web-application-php-cli"
    BASH_VAR=$( { docker exec $contname php /var/www/api/bin/console identity-provider:client:create doski --uri https://$main_domain/boards/oauth/callback --project boards; } 2>&1 )
    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
          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
          systemctl enable docker haproxy
          systemctl start docker
        fi       
      fi

      figlet mts-link-doski
      
      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 mts-link-doski update
      license_key=$(grep 'LICENSE_KEY' /opt/boards/gateway/.env | cut -d = -f 2)
      client_id=$(grep 'OAUTH_PROVIDER_CLIENT_ID' /opt/boards/auth/.env | cut -d = -f 2)
      client_secret=$(grep 'OAUTH_PROVIDER_CLIENT_SECRET' /opt/boards/auth/.env | cut -d = -f 2)
    fi

    inst_path=$(pwd)
    lic_data=$(curl -s 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")
    domain_signature=$(curl --silent https://$license/signature/{$license_key})
    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_storage=$first_word-s3.$domain_without_subdomain
    main_ip=$(getent ahostsv4 $main_domain | cut -d ' ' -f1 | sort -u)

    if [ "$MODE" = "INSTALL" ]; then
    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
    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
    string=$(echo $password | docker login --username $user https://$registry --password-stdin)
    if [[ $string != *"Login Succeeded"* ]]; then
      echo "Incorrect login or password"
      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 [[ "$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/$domain_without_subdomain.crt
      cp certs/$main_domain.key /etc/pki/$domain_without_subdomain.key
    fi

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

    sed -i -e "s/default_main_ip/$main_ip/g" group_vars/all/all.yml
    sed -i -e "s/default_domain_storage/$domain_storage/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_main_domain/$main_domain/g" group_vars/all/all.yml
    sed -i -e "s/default_cors_domain/$domain_without_subdomain/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
    sed -i -e "s/default_license_key/$license_key/g" group_vars/all/all.yml
    sed -i -e "s/default_license_server/$license/g" group_vars/all/all.yml
    sed -i -e "s/default_registry/$registry/g" group_vars/all/all.yml
    sed -i -e "s%default_inst_path%$inst_path%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=$(ss -tpnl | awk '!/\[::\]/&&/sshd/ {print $4}' | cut -d ":" -f 2 | head -n 1)
    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

    stage_runner stage_main first_init.yml
    cp version /opt/boards/version
    rm_src
    echo -e "\n\033[32mCongratulations\033[0m! The mts-link-doski platform has been \033[32msuccessfully\033[0m installed."
  ;;
esac
