#!/usr/bin/env bash

SYS_REL=$(lsb_release -sc | tail -n1)
REL=${1:-$SYS_REL}
RELEASE=${REL,,}
KEYFILE=cloudmaster-"$RELEASE".gpg

if [ ! -f "/usr/share/keyrings/cloudmaster-$RELEASE.gpg" ]; then
  case $RELEASE in
  focal)
    cat <<-EOF | tee /tmp/"$KEYFILE" >/dev/null
-----BEGIN PGP PUBLIC KEY BLOCK-----

mQGNBGLRJ+YBDADhf8n9GNg5Uc6KxNvMLiMy8POGbws0S8unTCY1EYVBtTlV4dbw
XH76yJVM3T8PFEgzoZu96wpPvCfr6k5eyPA4akI5DaMS24ftLhuIggvBceIKFW1r
gQqvJMll1RdB5jG8eBMBBbUlzrTFJyT8peRbpeD1iVW4+zRX6plWkQ+bA/uZrTgo
SfEsRIcG+xmdYeFc6OL/dOisBOngTDcmHJyzN1kEGtbRa8XedrCUmIWvgfAzgsDJ
BTmFsGylf/PRyw5xFnr6HetGASX9UDrwzJU3Vi79qhLmD3CbGbu3stxVaN98Bsdt
4TqR9xr61iq96gxk7aLN/A63vkQUgmPS6xperNySvV9CGSoIneh0AwqeZhtU2FYr
GttFsP72+5viTDTZZi1FB9qQ/S72Ui4pJ6GH4tMtdhOHHzb36mm4mX59BYyYHILT
1X0zS4JVkvBq7VAumSxPGdOGZFf/MxIFq6aVj2BR4YDMgoaqFGMlJknD6BQApgRm
2LEIAK79Ry6bYDUAEQEAAbRDRGVuaXMgRGF2eWRvdiAoU3lzdGVtIEFkbWluaXN0
cmF0b3IpIDxkZW5pcy5kYXZ5ZG92QGNsb3VkbWFzdGVyLnJ1PokBzgQTAQoAOBYh
BLtENKfz0elqFIW6Uos5ZMTF+EoFBQJi0SfmAhsDBQsJCAcCBhUKCQgLAgQWAgMB
Ah4BAheAAAoJEIs5ZMTF+EoF+cwL/0UmBNwNaBVEp17MXSIKFNOEwNTGV2mgoQ52
Xr8RPUNFqTHHZVD+pe5y2us6kN9cKCU+MUqU3L/fewoyLnNyWHZH2Q981jXxbmRA
Q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MpjNPhHs1fwnL2W/RF8pN+hma8FDs9YzuxKLPXofua9
6mkB11iFTQkY2Kjd/2IJCSpbgEv+u2qKO4QngsErdZyO2Sp4oKAIvuRb4EA0D19I
ZmRCN0iXEIptjSmsOl58ZBhULGJn2gjt0doAQlPRDkPstf8HBes0YcBhE9gvLRQA
sd3K5z1oKub7hz6bTJHY9LjyjBLbALilLfcT2JyP1Br0gYe905zcYFupkeuyQQYp
PtT1t/JMr5CCqKa8tBI68LknYirjouBh1x/T8+/6mM2BEhwRlBfjLHcqw+E4YQAe
un8rbVxR7iS2jlPRsA1QD1mNLbWUUKJ9CBVqt9fpHyV1QEhuH7V9H0lmshiPV/NL
Xna8Hwk=
=lGXO
-----END PGP PUBLIC KEY BLOCK-----
EOF
    ;;
  *)
    echo "'$RELEASE' release is not supported."
    exit 10
    ;;
  esac

  sudo apt-get -qq install apt-utils ca-certificates gpg
  cat /tmp/"$KEYFILE" | sudo gpg --dearmor -o /usr/share/keyrings/"$KEYFILE" && rm -f /tmp/"$KEYFILE"
fi

if [ ! -f "/etc/apt/sources.list.d/cloudmaster-$RELEASE.list" ]; then
  echo "deb [arch=amd64 signed-by=/usr/share/keyrings/$KEYFILE] https://nxs.cbi.cloudmaster.ru/repository/apt-$RELEASE/ $RELEASE main" | sudo tee /etc/apt/sources.list.d/cloudmaster-"$RELEASE".list >/dev/null
fi

sudo apt-get -qq update -o Dir::Etc::sourcelist="sources.list.d/cloudmaster-$RELEASE.list" -o Dir::Etc::sourceparts="-" -o APT::Get::List-Cleanup="0"
export BUILD_RELEASE=$RELEASE

echo "CloudMaster repository setup complete."
