#!/bin/bash
environment="09_25"
license="license-chat.mts-link.ru"

if [ -f /opt/boards/license/box.data ]; then
  export MODE=UPDATE
else
  export MODE=INSTALL
fi

if [ "$MODE" = "INSTALL" ]; then
apt update
apt install -y curl wget jq
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
fi

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 /usr/bin/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
  apt install -y docker.io logrotate 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
  figlet mts-link-doski
  read -p "Enter license key: " license_key
  status_code=$(curl --write-out %{http_code} --silent --output /dev/null https://$license/signature/{$license_key})
  if [[ "$status_code" -ne 200 ]] ; then
    echo "license_key not valid"
    exit 1
  fi
  read -p "Enter client id: " client_id
  read -p "Enter client secret: " client_secret
  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 hosts $main_domain | cut -d ' ' -f1)

  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=$(docker login --username $user --password $password https://$registry)
  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
  # spin='-\|/'
  # ansible-playbook fist_init.yml >> install.log 2>&1 &
  # pid=$!
  # i=0
  # while kill -0 $pid 2>/dev/null
  # do
  #   i=$(( (i+1) %4 ))
  #   printf "\r${spin:$i:1}"
  #   sleep .1
  # done
  # echo "installation complete"
  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

  spin='-\|/'
  docker run --rm --name ansible -v $(pwd):/playbook/ $registry/boards/ansible ansible-playbook -i inventory first_init.yml $ans_extra_args  >> install.log 2>&1
  pid=$!
  i=0
  while kill -0 $pid 2>/dev/null
  do
    i=$(( (i+1) %4 ))
    printf "\r${spin:$i:1}"
    sleep .1
  done
  if [[ $(tail -n3 install.log | grep -c failed=0) -eq 1 ]]; then
    systemctl restart logrotate
    cp version /opt/boards/version
    echo "Installation or update complete"
  else
    echo "Installation or update failed! Check install.log and fix error!"
  fi
  docker image rm $registry/boards/ansible 2>&1
  userdel -f -r ansinst
  rm -rf /home/ansinst
  rm /etc/sudoers.d/99-ansible-inst-user
  rm -rf group_vars
  rm -rf roles
  rm media_temp.tar.gz
  rm first_init.yml
  rm inventory
  ;;
esac

exit 0
