#!/usr/bin/env bash
set -e # Exit immediately if a command exits with a non-zero status

# --- Variables ---
ARCH="amd64"
DEBIAN_RELEASE="bookworm"
APP="saltstack"

# DEB822 Multi-value Fields (Arrays)
TYPES=("deb")
SUITES=("stable")
COMPONENTS=("main")

# Repo Details
REPO_URL="https://packages.broadcom.com/artifactory/saltproject-deb/"
REPO_DOMAIN="packages.broadcom.com"
KEY_URL="https://packages.broadcom.com/artifactory/api/security/keypair/SaltProjectKey/public"

# Pathing
KEY_DIR="/usr/share/keyrings"
KEY_FILE="${APP}-archive-keyring.gpg"
KEY_PATH="${KEY_DIR}/${KEY_FILE}"
SOURCES_AVAIL="/etc/apt/sources.list-available/${APP}.sources"
SOURCES_LINK="/etc/apt/sources.list.d/${APP}.sources"
PROXY_CONF="/etc/apt/apt.conf.d/99${APP}-proxy"

# --- Setup ---
sudo mkdir -p "${KEY_DIR}"
sudo mkdir -p /etc/apt/sources.list-available

# --- Proxy Bypass ---
echo "Configuring proxy bypass for ${REPO_DOMAIN}..."
echo "Acquire::HTTP::Proxy::${REPO_DOMAIN} \"DIRECT\";" | sudo tee "${PROXY_CONF}" >/dev/null

# --- GPG Key Handling & Validation ---
echo "Downloading GPG key..."
# Download and dearmor the GPG key
if curl -fsSL "${KEY_URL}" | sudo gpg --dearmor -o "${KEY_PATH}"; then
  if [ -s "${KEY_PATH}" ]; then
    echo "Success: GPG key downloaded and verified."
  else
    echo "Error: GPG key file is empty. Check the URL or network." >&2
    exit 1
  fi
else
  echo "Error: Failed to download or dearmor GPG key." >&2
  exit 1
fi

# --- DEB822 Heredoc Function ---
conf_print_salt_sources() {
  cat <<EOF
Enabled: yes
Types: ${TYPES[*]}
URIs: ${REPO_URL}
Suites: ${SUITES[*]}
Components: ${COMPONENTS[*]}
Architectures: ${ARCH}
Signed-By: ${KEY_PATH}
EOF
}

# Write to available and symlink to active
echo "Generating DEB822 source file..."
conf_print_salt_sources | sudo tee "${SOURCES_AVAIL}" >/dev/null
sudo ln -sf "${SOURCES_AVAIL}" "${SOURCES_LINK}"

# --- Package Installation ---
echo "Updating apt cache..."
sudo apt update

echo "Installing Salt components..."
sudo apt install -y \
  salt-master \
  salt-minion \
  salt-ssh \
  salt-syndic \
  salt-cloud \
  salt-api

# --- Shell Completions ---
echo "Installing shell completions..."
sudo mkdir -p /usr/share/bash-completion/completions/
sudo mkdir -p /usr/share/zsh/vendor-completions/

sudo curl -sL "https://raw.githubusercontent.com/saltstack/salt/develop/pkg/salt.bash" \
  -o /usr/share/bash-completion/completions/salt-common

sudo curl -sL "https://raw.githubusercontent.com/saltstack/salt/develop/pkg/zsh_completion.zsh" \
  -o /usr/share/zsh/vendor-completions/_salt

echo "SaltStack installation complete."
