#!/bin/bash

eval $(echo "$@" | grep -o "[^= ]\+ *= *[^ =]\+" | sed 's/ *= */=/')

: ${REPO_HOST="http://evi-build.eltex.loc:2080"}
: ${REPO_ADDRES="deb $REPO_HOST ot main"}
: ${REPO_FILE="/etc/apt/sources.list.d/evi.list"}

[[ -r "$REPO_FILE" ]] && rm -f "$REPO_FILE"
sudo echo "$REPO_ADDRES" | sudo tee "$REPO_FILE"
REPO_KEY=$(wget -q -O - "$REPO_HOST" | grep -q "gpg" && wget -q -O - "$REPO_HOST" | grep -o "[^\"]\+gpg[^\"]\+" | head -1)
[[ -z "$REPO_KEY" ]] && echo "GPG KEY NOT FOUND !!!" && exit 1
wget -q -O - $REPO_HOST/$REPO_KEY | sudo gpg --no-default-keyring --keyring gnupg-ring:/etc/apt/trusted.gpg.d/$REPO_KEY.gpg --import && sudo chmod +r /etc/apt/trusted.gpg.d/$REPO_KEY.gpg

sudo systemctl status evi-scud.service   2>/dev/null && echo "STOP: evi-scud"   && sudo systemctl stop evi-scud.service

sudo systemctl status evi-core.service   2>/dev/null && echo "STOP: evi-core"   && sudo systemctl stop evi-core.service

sudo systemctl status postgresql.service 2>/dev/null && echo "STOP: postgresql" && sudo systemctl stop postgresql.service

echo "UPDATE: evi-core evi-scud evi-core-web"
sudo apt update -qqqq
sudo apt install --allow-downgrades -yfqqqq postgresql evi-core=1.2.0-715 evi-scud=1.2.0-886 evi-core-web=1.2.0-4181


echo "START: postgresql"
sudo systemctl start postgresql.service

echo "START: evi-core"
sudo systemctl start evi-core.service

sleep 5
echo "START: evi-scud"
sudo systemctl start evi-scud.service

echo "DONE"

