#!/bin/bash
# Install manager from https://repo.cloudmatic.com - no GitLab access needed.
#
#   curl -fsSL https://repo.cloudmatic.com/files/manager/install.sh | sudo bash
#
# Installs the latest signed release into /opt/manager (MANAGER_DIR overrides).
# Refuses a non-empty directory: an existing manager updates itself with
# ./update.py --self-update.
set -euo pipefail

REPO=https://repo.cloudmatic.com
DEST=${MANAGER_DIR:-/opt/manager}
# the repository signing key; the key file is downloaded, this pins it
FINGERPRINT=66785BAE0B1E24636085094F297F4EFD0F22911C

die() { echo "error: $*" >&2; exit 1; }

for tool in curl gpg gpgv tar python3; do
    command -v "$tool" >/dev/null || die "$tool is required (apt install curl gnupg tar python3)"
done
if [ -e "$DEST" ] && [ -n "$(ls -A "$DEST" 2>/dev/null)" ]; then
    die "$DEST is not empty; update an existing manager with $DEST/update.py --self-update"
fi

tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
curl -fsSL "$REPO/keys/cloudmatic.gpg" -o "$tmp/key.gpg"
fpr=$(gpg --batch --show-keys --with-colons "$tmp/key.gpg" 2>/dev/null | awk -F: '/^fpr/{print $10; exit}')
[ "$fpr" = "$FINGERPRINT" ] || die "unexpected repository key $fpr"

fetch() {  # fetch <path> <dest>: download and check the detached signature
    curl -fsSL "$REPO/files/$1" -o "$2"
    curl -fsSL "$REPO/files/$1.asc" -o "$2.asc"
    gpgv --keyring "$tmp/key.gpg" "$2.asc" "$2" 2>/dev/null || die "bad signature on $1"
}

fetch manager/LATEST "$tmp/LATEST"
version=$(tr -d '[:space:]' < "$tmp/LATEST")
[[ "$version" =~ ^[0-9]{14}-[0-9a-f]+$ ]] || die "unexpected version '$version'"
fetch "manager/manager-$version.tar.gz" "$tmp/manager.tar.gz"

install -d -m 755 "$DEST"
tar -xzf "$tmp/manager.tar.gz" -C "$DEST" --no-same-owner
[ "$(cat "$DEST/VERSION")" = "$version" ] || die "release announces a different version"

# runtime dependencies (cmm needs Jinja2 and requests; init.py also cryptography)
if ! python3 -c 'import jinja2, requests, cryptography' 2>/dev/null; then
    if command -v apt-get >/dev/null && [ "$(id -u)" = 0 ]; then
        DEBIAN_FRONTEND=noninteractive apt-get install -y -qq python3-jinja2 python3-requests python3-cryptography >/dev/null
    else
        echo "install the Python dependencies: pip install -r $DEST/requirements.txt" >&2
    fi
fi

echo "manager $version installed in $DEST"
echo "  new deployment:      cd $DEST && cp seed.json.sample seed.json && edit it, then ./init.py"
echo "  existing deployment: cd $DEST && ./update.py"
