#!/bin/bash
BOLD=$(tput bold)
NORMAL=$(tput sgr0)

market_fqdn="$1"
while [ -z "$market_fqdn" ]; do
  echo -n "Введите IP(FQDN) адрес маркетплейса: "
  read market_fqdn
done

ENDPOINT="http://${market_fqdn}/brest-marketplace/index.html"
market_path="/var/www/html/brest-marketplace"
market_data_path="${market_path}/data"
market_index_path="${market_path}/index.html"
market_controlkey_path="${market_data_path}/controlkey"
loc_controlkey_path="/var/lib/one/remotes/market/brest/controlkey"
controlkey="$(! [ -f $loc_controlkey_path ] && echo "$(hostname)_$(date +%Y%m%d%H%M%S)" | base64 -w 0 > $loc_controlkey_path; cat $loc_controlkey_path)"

ssh_root_path="/root/.ssh"
if ! [ -f "${ssh_root_path}/id_rsa.pub" ]; then
    echo -e "y/n" | ssh-keygen -t rsa -f ${ssh_root_path}/id_rsa -P '' > /dev/null 2>&1
    check_root_key='x'
fi

function end_message() {
  echo -e "$1"
}

trap ctrl_c INT
function ctrl_c() {
        end_message "\n\n** Срыв настройки\n"
        [ -n "$check_root_key" ] && rm -rf ${ssh_root_path}/id_rsa.pub ${ssh_root_path}/id_rsa
        exit 0
}

function check_opennebula() {
  ssh -q root@${market_fqdn} "dpkg -s opennebula > /dev/null 2>&1"
  if [ $? -eq 0 ]; then
    echo "Узел ${market_fqdn} не может использоваться в качестве маркетплейса, т.к. на нем установлен пакет \"opennebula\""
    [ -n "$market_id" ] && /usr/bin/onemarket delete $market_id > /dev/null 2>&1
    exit -1
  fi
}

function connect_to_marketplace() {
  local authorized_keys="${ssh_root_path}/authorized_keys" ssh_key_oneadmin=($(cat /var/lib/one/.ssh/id_rsa.pub))
  # check control
  ssh -o BatchMode=yes -o ConnectTimeout=5 root@${market_fqdn} "
  test -f ${market_controlkey_path} || exit \$?;
  grep -wq '${ssh_key_oneadmin[1]}' $authorized_keys || exit \$?;
  cat ${market_controlkey_path} | head -n 1 | grep -wq \"^${controlkey}\$\" || exit \$?;
  max_level=\$(sudo pdp-ls -Mdn / | cut -d: -f2);
  root_level=\$(sudo pdpl-user root | tail -n1 | cut -d: -f2);
  [ \"\$max_level\" != \"\$root_level\" ] && exit -1;
  exit 0" > /dev/null 2>&1
  if [ $? -eq 0 ];then
    end_message "Доступ на управление получен"
    return 0
  fi
  local answer= message="Получить доступ на управление? (Да/Нет)[Нет]: "
  while [ -z "$answer" ];do
      echo -n "$message"
      read answer
      answer=$(echo ${answer,,})
      case $answer in
          'да'|'yes'|'y') answer="y";;
          'нет'|'no'|'n'|'') 
            ssh -o BatchMode=yes -o ConnectTimeout=5 root@${market_fqdn} "exit 0" > /dev/null 2>&1
            [ $? -eq 0 ] && return 0 || exit 0
            ;;
          *) answer=; message="Укажите \"Да\" или \"Нет\" (по усмолчанию: \"Нет\"): ";;
      esac
  done

  if [ "$answer" = "y" ];then
    local ssh_key_root=($(cat ${ssh_root_path}/id_rsa.pub))
    local CMD=$(cat << EOF

sudo bash -c "mkdir -p ${ssh_root_path}
if ! [ -f $authorized_keys ];then
    touch $authorized_keys
fi
if ! grep -wq '${ssh_key_oneadmin[1]}' $authorized_keys; then
    echo '${ssh_key_oneadmin[*]}' >> $authorized_keys
fi
if ! grep -wq '${ssh_key_root[1]}' $authorized_keys; then
    echo '${ssh_key_root[*]}' >> $authorized_keys
fi"
max_level=\$(sudo pdp-ls -Mdn / | cut -d: -f2);
root_level=\$(sudo pdpl-user root | tail -n1 | cut -d: -f2)
if [ \"\$max_level\" != \"\$root_level\" ]; then
  sudo pdpl-user -i \$max_level root > /dev/null 2>&1
  exit \$?
fi
EOF
)
    ssh -o BatchMode=yes -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${market_fqdn} "eval $CMD" > /dev/null 2>&1
    if [ $? -ne 0 ]; then
      local user_name=
      while [ -z "$user_name" ]; do
          echo -n "Введите имя локального администратора узла ${market_fqdn} (пользователь должен иметь безпарольный доступ через механизм sudo): "
          read user_name
      done
      ssh -o StrictHostKeyChecking=no ${user_name}@${market_fqdn} "eval $CMD"
      if [ $? -ne 0 ]; then
        end_message "Не удалось получить доступ на управление"
        exit -1
      fi
    fi

    check_opennebula

    ssh -o BatchMode=yes -o ConnectTimeout=5 root@${market_fqdn} "mkdir -p ${market_data_path}; test -f ${market_index_path} || touch ${market_index_path}; echo \"${controlkey}\" > ${market_controlkey_path}" > /dev/null 2>&1
    if [ $? -eq 0 ];then 
      end_message "Доступ на управление получен"
    fi
  fi
}


# edit /etc/apache2/apache2.conf on marketplace side
function edit_apache2_conf() {

  local apache_conf="/etc/apache2/apache2.conf" apache_conf_backup="${apache_conf}_backup_$(date +%y%m%d_%H%M%S)"
  local CMD=$(cat <<EOF

if ! \$(grep -Eq 'DISTRIB_ID *= *" *Astra *Linux *"' /etc/lsb-release); then
  exit 0
fi
if \$(grep -Eq '^ *AstraMode +off' ${apache_conf}); then
  exit 0
fi
cp ${apache_conf} ${apache_conf_backup}
if grep -Eq '^ *#* *AstraMode +o[nf]f*' ${apache_conf};then
    sed -i -e '/[ ]*AstraMode [ ]*on/c AstraMode off' -e '/[ ]*#[#]*[ ]*AstraMode [ ]*[on|off]/c AstraMode off' ${apache_conf}
    del_array=(\$(grep -En '^ *AstraMode +o[nf]f*' ${apache_conf} | awk -F: 'NR > 1 {print \$1}'))
    if [ -n "\$del_array" ];then 
        del_lines=\$(echo \${del_array[*]} | sed 's/ /d;/g')
        sed -i "\${del_lines}d" ${apache_conf}
    fi
else
    echo "AstraMode off" >> ${apache_conf}
fi
systemctl restart apache2
if [ $? -eq 0 ];then
    rm ${apache_conf_backup}
else
    cp ${apache_conf_backup} ${apache_conf}
    systemctl restart apache2
fi
EOF
)

  if ssh -o BatchMode=yes -o ConnectTimeout=5 root@${market_fqdn} "test -f ${apache_conf}" > /dev/null 2>&1; then
        ssh -o BatchMode=yes -o ConnectTimeout=5 root@${market_fqdn} "eval ${CMD}" > /dev/null 2>&1
  else
      end_message "Не обнаружен кофигурационный файл ${apache_conf} на стороне ${market_fqdn}. Маркетплейс не настроен."
  fi
}

if ! ping -i0.5 -c2 $market_fqdn > /dev/null 2>&1;then
  echo "Нет доступа к адресу $market_fqdn."
  exit -1
fi

if ssh -o BatchMode=yes -o ConnectTimeout=5 root@${market_fqdn} "exit 0" > /dev/null 2>&1; then
  check_opennebula
fi

for (( ch = 0; ch < 3; ch++ )); do
   market_list="$(onemarket list -x)"
  if [ $? -eq 0 ] ; then
    break
  else
    market_list=
    sleep 3
  fi
done
[ -z "$market_list" ] && exit -1

market_id="$(echo "$market_list" | xmlstarlet sel -t -v '/MARKETPLACE_POOL/MARKETPLACE[TEMPLATE[MARKET_MAD="brest"][ENDPOINT="'$ENDPOINT'"]]/ID' -n)"
if [ -z "$market_id" ];then
  tmp_dump_path="/var/tmp/one-dump/"
  mkdir -p ${tmp_dump_path}
  work_dir=$tmp_dump_path/$(($(date +%s%N)/1000000))
  mkdir $work_dir
  name_market= 
    while [ -z "$name_market" ];do
        echo -en "Введите имя маркетплейса: "
        read name_market
        check_market_name=$(/usr/bin/onemarket list --csv | awk -F',' '{if($2 == "'"${name_market}"'")print $1}')
        if [ -n "${check_market_name}" ]; then
          echo "Имя \"${name_market}\" уже занято (ID ${check_market_name})"
          name_market=
        fi
    done
  echo -e "NAME = \"$name_market\"\nMARKET_MAD = \"brest\"\nENDPOINT = \"${ENDPOINT}\"" > ${work_dir}/appmarket.conf
  market_id=$(/usr/bin/onemarket create ${work_dir}/appmarket.conf)
  if [ $? -eq 0 ]; then
    market_id="$(echo "$id_market" | cut -d' ' -f2)"
  else
    rm -rf $work_dir
    exit -1
  fi
  rm -rf $work_dir
fi

connect_to_marketplace

edit_apache2_conf
