#!/bin/bash
# Served at https://install.sessionrouter.com - usage:
#   curl -fsSL https://install.sessionrouter.com | bash
set -uo pipefail

REPO_HOST="${SR_APT_HOST:-install.sessionrouter.com}"
KEYRING=/usr/share/keyrings/sessionrouter-archive-keyring.asc
LOG=/var/log/sessionrouter-install.log
: > "$LOG"

if [ -t 1 ]; then
    GREEN=$'\033[0;32m'; RED=$'\033[0;31m'; BOLD=$'\033[1m'; RESET=$'\033[0m'
else
    GREEN=""; RED=""; BOLD=""; RESET=""
fi

step() { printf '%s%s%s' "$BOLD" "$1" "$RESET"; }
ok()   { printf ' %s[OK]%s\n' "$GREEN" "$RESET"; }

fail() {
    printf ' %s[FAILED]%s\n' "$RED" "$RESET" >&2
    echo "" >&2
    echo "  $1" >&2
    echo "  Full log: $LOG" >&2
    echo "" >&2
    tail -n 20 "$LOG" >&2
    exit 1
}

if [ "$(id -u)" -ne 0 ]; then
    echo "This installer needs root." >&2
    echo "Try: curl -fsSL https://${REPO_HOST} | sudo bash" >&2
    exit 1
fi

if dpkg -l sessionrouter 2>/dev/null | grep -q '^ii'; then
    echo "${BOLD}Session Router is already installed.${RESET}" >&2
    if systemctl is-active --quiet cpaas.service; then
        echo "  It's currently running." >&2
    else
        echo "  It's currently installed but not running (systemctl start cpaas.service)." >&2
    fi
    echo "" >&2
    echo "  To reinstall from a clean state, run the uninstaller first:" >&2
    echo "    curl -fsSL https://${REPO_HOST}/uninstall.sh | bash" >&2
    echo "  Then run this installer again." >&2
    exit 1
fi

export DEBIAN_FRONTEND=noninteractive
export NEEDRESTART_MODE=a

echo "${BOLD}Session Router Installer${RESET}"
echo ""

step "Installing Session Router..."
{
    curl -fsSL "https://${REPO_HOST}/repo-signing-key.asc" -o "$KEYRING" &&
    echo "deb [signed-by=${KEYRING}] https://${REPO_HOST}/ stable main" > /etc/apt/sources.list.d/sessionrouter.list &&
    apt-get update -qq &&
    apt-get install -y -qq sessionrouter
} >> "$LOG" 2>&1
if [ $? -ne 0 ]; then
    fail "Package installation failed."
fi
ok

# --- TEMPORARY: pre-fills a test activation key so the whole install is one
# command while we don't have real license issuance yet. Remove this block
# once that's in place - see packaging/README.md.
if ! grep -q '^activation_key=' /etc/sessionrouter/env 2>/dev/null; then
    cat >> /etc/sessionrouter/env << 'EOF'
activation_key=912a567c-9515-4f11-a474-cca9c79b0ce3
license_server_url=http://159.69.81.138:8090/api/activate
EOF
fi
# --- END TEMPORARY ---

step "Activating license..."
START_TIME="$(date '+%Y-%m-%d %H:%M:%S')"
if ! systemctl start cpaas.service >> "$LOG" 2>&1; then
    fail "Could not start the service (systemctl start cpaas.service failed)."
fi

STATUS=""
for _ in $(seq 1 60); do
    RECENT="$(journalctl -u cpaas.service --no-pager -o cat --since "$START_TIME" 2>/dev/null)"
    if echo "$RECENT" | grep -q "CPaaS Server is ready to serve"; then
        STATUS="ready"
        break
    fi
    if echo "$RECENT" | grep -qE "activation rejected|Authentication failed|Not activated"; then
        STATUS="rejected"
        break
    fi
    sleep 1
done

case "$STATUS" in
    ready)
        ok
        ;;
    rejected)
        printf ' %s[FAILED]%s\n' "$RED" "$RESET" >&2
        echo "" >&2
        echo "  License activation was rejected. Recent logs:" >&2
        echo "$RECENT" | tail -n 10 >&2
        exit 1
        ;;
    *)
        printf ' %s[TIMED OUT]%s\n' "$RED" "$RESET" >&2
        echo "" >&2
        echo "  Activation is taking longer than expected. Check:" >&2
        echo "    journalctl -u cpaas.service -f" >&2
        exit 1
        ;;
esac

IP="$(hostname -I 2>/dev/null | awk '{print $1}')"
echo ""
echo "${GREEN}${BOLD}Session Router is installed and running.${RESET}"
echo ""
echo "  Admin UI:  http://${IP:-<this-box-ip>}:8080/login"
echo "  Default login: admin / Pa\$\$w0rd  ${BOLD}(change this now)${RESET}"
echo "  Logs:      journalctl -u cpaas.service -f"
echo ""
