#!/usr/bin/env bash

. /usr/share/dosis2/bin/shell-support-functions

DAFECONFIG='/opt/dosis2/etc/custom/dosisConfig.xml'
API_URL="http://eris.swamp.alex:8675/v1/teleport/join-token"
API_TOKEN=7a056bc1-3dc2-4c1c-84de-a7df99983fea
HOSTNAME_VALUE="$(hostname -s)"
HOSTNAME_UPPER="$(printf '%s' "${HOSTNAME_VALUE}" | tr '[:lower:]' '[:upper:]')"
TOKEN_FILE="./teleport-join.token"
VPN_P12_FILE="/etc/openvpn/vpn_awse2c/vpn_awse2c/${HOSTNAME_UPPER}_vpn_awse2c.p12"

read_dafe_tag() {
    local config_file="$1"

    [[ -f "$config_file" ]] || return 1

    perl -0ne 'if (m{<property\s+name="DafeTag">.*?<value>\s*([^<]+?)\s*</value>}s) { print $1 }' "$config_file"
}

apt update || echo "WARNING: apt update failed, continuing..."
apt install -y curl wget sshfs sshpass jq

CUSTNUM="$(psql -U dsuper -d dosis2 -tAc "SELECT value FROM site.view_site_settings WHERE tag='CUSTOMER_NUMBER' limit 1")"

if [[ -z "$CUSTNUM" ]]; then
    echo "ERROR: Unable to determine CUSTOMER_NUMBER from site.view_site_settings."
    exit 1
fi

DAFETAG="$(read_dafe_tag "$DAFECONFIG" | tr -d '[:space:]' || true)"

if [[ -z "$DAFETAG" ]]; then
    echo "ERROR: Unable to determine DafeTag from $DAFECONFIG."
    exit 1
fi

MACHINE_ROLE='site-server'
NODE_NAME="ss${CUSTNUM}"

echo "Detected machine role: ${MACHINE_ROLE} (DafeTag=${DAFETAG})"

TELEPORT_CONFIG='/etc/teleport.yaml'
TELEPORT_PROXY='manchac.teleport.sh:443'

echo "Installing Teleport agent..."

if [[ -f "$TELEPORT_CONFIG" ]]; then
    BACKUP_FILE="${TELEPORT_CONFIG}.$(date +%Y%m%d%H%M%S).bak"
    echo "Backing up existing config to $BACKUP_FILE"
    mv "$TELEPORT_CONFIG" "$BACKUP_FILE"
fi

if [[ ! -f "/usr/local/bin/yq" ]]; then
    wget https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O /usr/local/bin/yq && chmod +x /usr/local/bin/yq
fi

curl "https://manchac.teleport.sh:443/scripts/install.sh" | bash

echo "Refreshing DNS cache"
if systemctl is-active --quiet systemd-resolved; then
    systemctl restart systemd-resolved
    systemd-resolve --flush-caches
fi

if [ ! -r "${VPN_P12_FILE}" ]; then
    echo "ERROR: Cannot read P12 file: ${VPN_P12_FILE}" >&2
    find /etc/openvpn/vpn_awse2c -maxdepth 3 -type f -name '*.p12' -ls >&2
    exit 1
fi

RESPONSE_FILE="$(mktemp)"
trap 'rm -f "${RESPONSE_FILE}"' EXIT

response="$(curl -fsS \
  -X POST "${API_URL}" \
  -H "Authorization: Bearer ${API_TOKEN}" \
  -F "hostname=${HOSTNAME_UPPER}" \
  -F "customer_num=${CUSTNUM}" \
  -F "p12_file=@${VPN_P12_FILE}")"

join_token="$(echo "${response}" | jq -r '.token')"

if [ -z "${join_token}" ] || [ "${join_token}" = "null" ]; then
  echo "Token was not returned by broker" >&2
  echo "${response}" >&2
  exit 1
fi

printf '%s\n' "${join_token}" > "${TOKEN_FILE}"

echo "Wrote Teleport join token to ${TOKEN_FILE}"

if [[ ! -f "./teleport-join.token" ]]; then
    echo "ERROR: Join token not found. Exiting."
    exit 1
fi

cp ./teleport-join.token /opt/dosis2/etc/teleport-join.token

echo "Writing $TELEPORT_CONFIG..."
teleport node configure \
 --output=file:///etc/teleport.yaml \
 --token=/opt/dosis2/etc/teleport-join.token \
 --proxy=manchac.teleport.sh:443 \
 --labels=custnum=${CUSTNUM} \
 --node-name="${NODE_NAME}"

yq -i '
  .ssh_service.pam.enabled = true |
  .ssh_service.pam.service_name = "sshd" |
  .ssh_service.commands = [
    {
      "name": "hostname",
      "command": ["hostname"],
      "period": "1h0m0s"
    },
    {
      "name": "osversion",
      "command": ["lsb_release", "-sd"],
      "period": "24h0m0s"
    }
  ]
' /etc/teleport.yaml

chmod 600 "$TELEPORT_CONFIG"

echo "Enabling Teleport..."
systemctl enable teleport

echo "Starting Teleport..."
systemctl restart teleport

echo
echo "Teleport version:"
teleport version

