#!/bin/bash

# Install latest salt repo for ubuntu / debian from salt repo
LINUX_VERSION=$(lsb_release -is)
LINUX_RELEASE=$(lsb_release -rs)
case $LINUX_VERSION in
	Ubuntu)
		echo "Ubuntu detected"
		case $LINUX_RELEASE in
			22.04)
				curl -fsSL -o /usr/share/keyrings/salt-archive-keyring.gpg https://repo.saltproject.io/py3/ubuntu/20.04/amd64/3004/salt-archive-keyring.gpg
    			echo "deb [signed-by=/usr/share/keyrings/salt-archive-keyring.gpg arch=amd64] https://repo.saltproject.io/py3/ubuntu/20.04/amd64/3004 focal main" | tee /etc/apt/sources.list.d/salt.list
				;;
			20.04)
				curl -fsSL -o /usr/share/keyrings/salt-archive-keyring.gpg https://repo.saltproject.io/py3/ubuntu/20.04/amd64/3004/salt-archive-keyring.gpg
    			echo "deb [signed-by=/usr/share/keyrings/salt-archive-keyring.gpg arch=amd64] https://repo.saltproject.io/py3/ubuntu/20.04/amd64/3004 focal main" | tee /etc/apt/sources.list.d/salt.list
				;;
			18.04)
				curl -fsSL -o /usr/share/keyrings/salt-archive-keyring.gpg https://repo.saltproject.io/py3/ubuntu/18.04/amd64/3004/salt-archive-keyring.gpg
    			echo "deb [signed-by=/usr/share/keyrings/salt-archive-keyring.gpg arch=amd64] https://repo.saltproject.io/py3/ubuntu/18.04/amd64/3004 bionic main" | tee /etc/apt/sources.list.d/salt.list
				;;
			*)
				# other ubuntu version, keep salt-minion from original repo
				;;
		esac
		;;
	Debian)
		echo "Debian detected"
		case $LINUX_RELEASE in
			11)
				curl -fsSL -o /usr/share/keyrings/salt-archive-keyring.gpg https://repo.saltproject.io/py3/debian/11/amd64/3004/salt-archive-keyring.gpg
				echo "deb [signed-by=/usr/share/keyrings/salt-archive-keyring.gpg arch=amd64] https://repo.saltproject.io/py3/debian/11/amd64/3004 bullseye main" | tee /etc/apt/sources.list.d/salt.list
				# install apparmor as needed for docker
				apt install apparmor
				;;
			10)
				curl -fsSL -o /usr/share/keyrings/salt-archive-keyring.gpg https://repo.saltproject.io/py3/debian/10/amd64/3004/salt-archive-keyring.gpg
				echo "deb [signed-by=/usr/share/keyrings/salt-archive-keyring.gpg arch=amd64] https://repo.saltproject.io/py3/debian/10/amd64/3004 buster main" | tee /etc/apt/sources.list.d/salt.list
				;;
			*)
				# other debian version, keep salt-minion from original repo
				;;
		esac
		;;
	*)
		# other linux version
		;;
esac


################################################################################
apt-get update && apt install -y --asume-yes true git salt-minion
################################################################################


# Init salt-minion (masterless)
cp /mnt/repo-base/deployment/salt/init-config/masterless.conf /etc/salt/minion.d/

# Run repo init (might run a few minutes)
echo "System update and packages installation .."
salt-call state.apply docker-compose


# init repo
bash /mnt/repo-base/scripts/init-repo.sh $ENVIRONMENT
