#!/bin/bash

###
### Центр Обновления
###
### Copyright (C) ООО Кейсистемс 2020
###


# === Определяем каталог выполнения текущего скрипта ==================================
dks_bashfile_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
ks_inst_path="/opt"
# Файл списка софтов
ks_list_file="${dks_bashfile_dir}/ks_list.json"
dks_folders_file="${dks_bashfile_dir}/dks_folders"
rm -f ${ks_list_file}
touch ${ks_list_file}


cat << EOF >> ${ks_list_file}
[
EOF


function fn_get_lvl_01() {
local ks_list_file=$1
#local dir=$2
#local name=$3
#local type=$4
#local comma=$5
#local inifile=$6

local comma=$2
local inifile=$3

local dir=$(dirname ${inifile})
local name=$(basename ${dir})
local isdks=${name:0:4}
local type
#local type=$(echo ${name} | rev | cut -d"-" -f2- | rev | sed 's/.*-//')
if [ "$isdks" = "dks-" ];then
	type=$(echo ${name:4} | sed 's/-.*//')
else
	type=$(echo ${name} | sed 's/-.*//')
fi;
local inidata="{}"

if [ -f "$inifile" ];then
	name=$(iconv -f WINDOWS-1251 -t UTF-8 ${inifile} | grep -oP '"name"\s*:\s*"\K.*?(?=")' | head -1)
	dir=$(iconv -f WINDOWS-1251 -t UTF-8 ${inifile} | grep -oP '"rootdir"\s*:\s*"\K.*?(?=")' | head -1)
	type=$(iconv -f WINDOWS-1251 -t UTF-8 ${inifile} | grep -oP '"type"\s*:\s*"\K.*?(?=")' | head -1)
	inidata=$(iconv -f WINDOWS-1251 -t UTF-8 ${inifile})
fi;
local version=$(echo ${dir} | sed 's/.*-//')

local is_exists="0"
local is_install="0"

if [ -d "${dir}" ];then
  is_exists="1"

  #Докер
  if [ "${type}" = "docker" ];then
    if [ -f "/usr/bin/docker" ];then
		is_install="1"
		version=($(docker -v | sed 's/.*version //' | sed 's/,.*//'))
    fi;
    #is_running=$(echo $(systemctl is-active docker.service))
    #if [ "${is_running}"="active" ]; then
    #  is_running="1"
    #fi;
  fi;

  #СУБД-КС
  if [ "${type}" = "pgsqlks" ];then
    is_install="1"
  fi;

  #WEB-Сервер-КС
  if [ "${type}" = "wsks" ];then
    is_install="1"
  fi;

  #PGBOUNCER
  if [ "${type}" = "pgbouncer" ];then
    is_install="1"
  fi;
  
  #TaskScheduler-КС
  if [ "${type}" = "tshks" ];then
    is_install="1"
  fi;

  #RMQ-КС Докер
  if [ "${type}" = "rmqks" ];then
    is_install="1"
  fi;
fi;

# пишем первый уровень дерева
cat << EOF >> ${ks_list_file}
{
 "name" : "${name}",
 "version": "${version}",
 "type" : "${type}",
 "is_exists" : "${is_exists}",
 "is_install" : "${is_install}",
 "rootdir" : "${dir}",
 "controldir" : "${dir}",
 "ini" : ${inidata},
 "nodes" : [
EOF

local ks_inst_path_dks=$ks_inst_path/dks-
local offset=$(echo ${#ks_inst_path_dks})
local dksless=${dir:$offset}

# пишем второй  уровень дерева
if [ "${type}" = "docker" ];then
  fn_get_lvl_02 ${ks_list_file} ${type} "${dir}" "/usr/bin" "dockerd" "Docker-CE" ${version}
fi;

#СУБД-КС
if [ "${type}" = "pgsqlks" ];then
  fn_get_lvl_02 ${ks_list_file} ${type} "${dir}" "/var/lib" ${dksless}"_[1-9]" "СУБД-КС" ${version}
fi;

#WEB-Сервер-КС
if [ "${type}" = "wsks" ];then
  fn_get_lvl_02 ${ks_list_file} ${type} "${dir}" "/opt" ${dksless}"_[0-9]" "WEB-Сервер-КС" ${version}
fi;

#PGBOUNCER
if [ "${type}" = "pgbouncer" ];then
  fn_get_lvl_02 ${ks_list_file} ${type} "${dir}" "/opt" ${dksless}"_[1-9]" "PgBouncer" ${version}
fi;

#TaskScheduler-КС
if [ "${type}" = "tshks" ];then
  fn_get_lvl_02 ${ks_list_file} ${type} "${dir}" "/opt/"${type}-${version} ${type}"_[1-9]" "TaskScheduler-КС" ${version}
fi;

#RMQ-КС Докер
if [ "${type}" = "rmqks" ];then
  fn_get_lvl_02 ${ks_list_file} ${type} "${dir}" "/opt" ${dksless}"_[1-9]" "RMQ-КС Докер" ${version}
fi;

cat << EOF >> ${ks_list_file}
  ]
}${comma}
EOF

}
function fn_get_lvl_02() {
local ks_list_file=$1
local type=$2
local controldir=$3
local search_path=$4
local serach_template=$5
local title=$6
local version=$7

local is_running="0"
local service
local alist
local item
local dir
local port
local installdir
local comma
local index
local alen
local rootdir="${controldir}"
local serverip=""
local serverport=""
local titlename="$title"
alist=($(ls ${search_path} | grep "${serach_template}"))

alen=${#alist[*]}

if [ "${alen}" = "0" ];then
  return 0;
fi;

alen=$((${alen}-1))

for index in ${!alist[*]}
do
  titlename="$title"
  item=${alist[${index}]}
  dir=${item}
  port=$(echo ${item} | sed 's|.*_||')
  tagname=$(echo ${item} | sed -r 's/_.+//')
  installdir="${search_path}/${item}"
  if [ "${type}" = "docker" ];then
    service="docker.service"
    installdir="${search_path}"
    port=""
  fi;

  if [ "${type}" = "pgsqlks" ];then
    service="${item}.service";
	serverip="$(echo $(hostname -I | awk '{print $1}'))";
  fi;

  if [ "${type}" = "wsks" ];then
    service="${tagname}_${port}.service";
    controldir="${installdir}/ctl";
  fi;

  if [ "${type}" = "pgbouncer" ];then
    service="${tagname}_${port}.service";
	controldir="${installdir}/ctl";
	serverip=$(cat ${installdir}/conf.d/pgbouncer_db.ini | grep -oP 'host\s*=\s*\K.*?(?=(\s|$))')
	serverport=$(cat ${installdir}/conf.d/pgbouncer_db.ini | grep -oP 'port\s*=\s*\K.*?(?=(\s|$))')
  fi;
  
  if [ "${type}" = "tshks" ];then
    service="${type}-${version}_${port}.service";
  fi;
  
  if [ "${type}" = "rmqks" ];then
    service="${tagname}_${port}.service";
  fi;

  if [ "$port" != "" ]; then
	titlename="${titlename}"
  fi;
  service_inst=$(service_exists ${service})
  is_running=$(echo $(systemctl is-active ${service}))
  if [ "${is_running}" = "active" ]; then
    is_running="1"
  else
    is_running="0"
  fi;

  if [ "${index}" = "${alen}" ];then
    comma=""
  else
    comma=","
  fi;

  

#debug
#echo "item = ${item} index = ${index} alen=${alen} comma=${comma} "

cat << EOF >> ${ks_list_file}
             {
              "name" : "${titlename}",
			  "version": "${version}",
			  "type" : "${type}",
              "port" : "${port}",
              "rootdir" : "${rootdir}",
              "installdir" : "${installdir}",
              "controldir" : "${controldir}",
              "service" : "${service}",
              "service_inst" : "${service_inst}",
              "is_running" : "${is_running}",
              "serverip" : "${serverip}",
              "serverport" : "${serverport}",
              "nodes" : [
EOF

  if [ "${type}" = "wsks" ];then
    fn_get_lvl_03 ${ks_list_file} ${type} "${installdir}" "${installdir}/www/html" "wsks_[1-9]" "Приложение" ${version}
  fi;

cat << EOF >> ${ks_list_file}
                        ]
             }${comma}
EOF

done
}

function fn_get_lvl_03(){
local ks_list_file=$1
local type=$2
local controldir=$3/ctl
local tardir=${controldir}/tar_files
local search_path=$4
local serach_template=$5
local title=$6
local pversion=$7

local alist
local item
local dir
local port
local comma
local index
local alen
local apptype
local archive
local lapptype
local rootdir
local is_running="0"
alist=($(ls ${search_path} | grep "${serach_template}"))

alen=${#alist[*]}

if [ "${alen}" = "0" ];then
  return 0;
fi;

alen=$(($alen-1))

for index in ${!alist[*]}
do
  item=${alist[${index}]}
  dir=${item}
  port=$(echo ${item} | sed 's|.*_||')
  if [ "${type}" = "wsks" ];then
    if [ -f ${search_path}/${item}/wskstype ];then
      apptype=$(param_val type ${search_path}/${item}/wskstype)
	  archive=$(param_val archive ${search_path}/${item}/wskstype)
	  lapptype=$(echo ${apptype} | tr '[:upper:]' '[:lower:]')
      title=$(fn_get_wsks_type ${apptype})
	  title="${title}"
    else
      apptype="неизвестно"
    fi;
	rootdir="$ks_inst_path/dks-app-download/$lapptype-$pversion"
	is_running=$(echo $(ps -aux | grep "[/]opt/.dotnet/dotnet /var/www/html/wsks_${port}"))
	if [ "${is_running}" != "" ]; then
		is_running="1"
	fi;
  fi;

  if [ "${index}" = "${alen}" ];then
    comma=""
  else
    comma=","
  fi;
cat << EOF >> ${ks_list_file}
                         {
                          "name" : "${title}",
						  "type" : "${apptype}",
						  "version" : "${pversion}",
                          "port" : "${port}",
                          "rootdir" : "${rootdir}",
						  "archive" : "${archive}",
                          "installdir" : "${search_path}/${item}",
                          "controldir" : "${controldir}",
						  "is_running" : "${is_running}"
                         }${comma}
EOF
done
}

function fn_get_wsks_type(){
local retval
case $1 in
        wBKS)
          retval="Бюджет-NEXT"
          ;;
        sBKS)
          retval="Смарт Бюджет"
          ;;
        sSiUp)
          retval="Сервис ОД и ЭЦП"
          ;;
        sUPDS)
          retval="Сервис Обновлений"
          ;;
        wSVOD)
          retval="Веб Свод"
          ;;
        sSVOD)
          retval="Смарт Свод"
          ;;
        wSA)
          retval="Сервис Авторизации"
          ;;
        wRVZ)
          retval="Ревизор-Веб"
          ;;
        sRVZ)
          retval="Ревизор-Смарт"
          ;;
        wDWH)
          retval="Проект-Веб ПРО"
          ;;
        sDWH)
          retval="Проект-Смарт ПРО"
          ;;
        wADM)
          retval="Администратор-WEB"
          ;;
        sADM)
          retval="Администратор-СМАРТ"
          ;;
        sSMT)
          retval="Смета-СМАРТ"
          ;;
        wSWrk)
          retval="Сервис Воркеров"
          ;;
        wSBck)
          retval="Сервис Резервного копирования"
          ;;
        *)
          retval="неизвестно"
          ;;
esac
echo "${retval}"
}

function param_val {
    sed -n "s/${1}=//p" $2 2> /dev/null
}

function service_exists() {
    local n=$1
	local retval
    if [[ $(systemctl list-units --all -t service --full --no-legend "$n" | cut -f1 -d' ') == $n ]]; then
        retval=1
    else
        retval=0
    fi
	echo "${retval}"
	#return ${retval}
}

#fn_get_lvl_01 ${ks_list_file} "dks-docker-ce-19.03.4" "Сервис Докер (19.03.4)"     "docker"    ","
#fn_get_lvl_01 ${ks_list_file} "dks-pgsqlks-12.1"      "СУБД-КС Докер (12.1)"       "pgsqlks"   ","
#fn_get_lvl_01 ${ks_list_file} "dks-wsks-2.2.8"        "WEB-Сервер-КС Докер (12.1)" "wsks"      ","
#fn_get_lvl_01 ${ks_list_file} "dks-pgbouncer-1.12.0"  "PgBouncer Докер (1.12.0)"   "pgbouncer" ""

declare -a files
declare -a dockers
find ${ks_inst_path} -type d -not -path "/opt/dks-app-download" -name "tshks-*"  2>&1> ${dks_folders_file} | { grep -v 'find:' >&2; [ $? -eq 1 ]; }
find ${ks_inst_path} -type d -not -path "/opt/dks-app-download" -name 'dks-*' 2>&1>> ${dks_folders_file} | { grep -v 'find:' >&2; [ $? -eq 1 ]; }
find ${ks_inst_path}/dks-app-download -type d -not -path "/opt/dks-app-download" 2>&1>> ${dks_folders_file} | { grep -v 'find:' >&2; [ $? -eq 1 ]; }
dockers=($(cat ${dks_folders_file} | grep dks-docker))
dcount=$(( ${#dockers[*]} ))
if [[ $dcount -eq 0 ]]
then
	docker_exist=$(service_exists docker.service)
	if [[ $docker_exist -eq 1 ]]
	then
		version=($(docker -v | sed 's/.*version //' | sed 's/,.*//'))
		echo /opt/dks-docker-$version >> ${dks_folders_file}
	fi
fi
files=($(cat ${dks_folders_file}))
#files=($(find ${ks_inst_path} -type d -name 'dks-*' -not -path "/opt/dks-app-download"))
#if [ -d "${ks_inst_path}/dks-app-download" ]; then
	#find ${ks_inst_path}/dks-app-download -type d -not -path "/opt/dks-app-download" 2>&1> ${dks_folders_file} | { grep -v 'find:' >&2; [ $? -eq 1 ]; }
	#files+=($(cat ${dks_folders_file}))
	#files+=($(find ${ks_inst_path}/dks-app-download -type d -not -path "/opt/dks-app-download"))
#fi
#files=($(find ${ks_inst_path} -name 'setupsrv.ini'))
fcount=$(( ${#files[*]} ))
if [[ $fcount -gt 0 ]]
then
	lastfile=${files[$fcount - 1]}
	for file in "${files[@]}"
	do
		# прямо тут в качестве аргументов нужно выдернуть и прокинуть "commands" и "files"
		if [[ $file == $lastfile ]]
		then
			fn_get_lvl_01 ${ks_list_file}  "" "${file}/setupsrv.ini"
		else
			fn_get_lvl_01 ${ks_list_file}  "," "${file}/setupsrv.ini"
		fi
	done
fi
cat << EOF >> ${ks_list_file}
]
EOF


cat ${ks_list_file}
rm -f ${ks_list_file}

exit;





