#!/bin/sh
set -eu
mkdir -p /etc/yc/unified_agent
folder_id=$(\
  curl -H "Metadata-Flavor:Google" \
    -s http://169.254.169.254/computeMetadata/v1/instance/vendor/folder-id \
)
cat > /etc/yc/unified_agent/config.yml <<END
# THIS IS A GENERATED FILE. DO NOT EDIT.
storages:
  - name: yc_metrics_storage
    plugin: fs
    config:
      directory: /var/lib/yc/unified_agent/yc_metrics_storage
      max_partition_size: 100mb
      max_segment_size: 10mb
channels:
  - name: yc_metrics_channel
    channel:
      pipe:
        - storage_ref:
            name: yc_metrics_storage
      output:
        plugin: yc_metrics
        config:
          url: "https://monitoring.api.cloud.yandex.net/monitoring/v2/data/write"
          folder_id: "$folder_id"
          iam:
            cloud_meta: { }
routes:
  - input:
      id: linux_metrics_input
      plugin: linux_metrics
      config:
        poll_period: 60s
        namespace: sys
    channel:
      channel_ref:
        name: yc_metrics_channel
  - input:
      id: agent_metrics_input
      plugin: agent_metrics
      config:
        poll_period: 60s
        namespace: ua
    channel:
      pipe:
        - filter:
            plugin: filter_metrics
            config:
              match: "{scope=health}"
      channel_ref:
        name: yc_metrics_channel
END
mkdir -p /lib/systemd/system
cat >/lib/systemd/system/unified_agent_installer.service <<END
[Unit]
Description=yc unified agent installer
Before=unified_agent.service

[Service]
Type=oneshot
ExecStart=/bin/sh -c "curl -s https://downloads.adsw.io/sre/yc-unified-agent/install.sh | /bin/sh"

[Install]
WantedBy=multi-user.target
END
systemctl enable unified_agent_installer.service
cat >/lib/systemd/system/unified_agent.service <<END
[Unit]
Description=yc unified agent
After=network.target

[Service]
Type=simple
MemoryLimit=300M
ExecStart=/bin/unified_agent --config /etc/yc/unified_agent/config.yml
KillMode=process
Restart=always
RestartSec=2s

[Install]
WantedBy=multi-user.target
END

if [ ! -f /bin/unified_agent ]; then 
  NAME=""
  VERSION_ID=""
  [ -e /etc/os-release ] && . /etc/os-release
  ua_version=$(curl -s "https://downloads.arenadata.io/sre/yc-unified-agent/versions" | while IFS=":" read -r k v; do
    [ "$k" = "default" ] || [ "$k" = "$NAME $VERSION_ID" ] && printf '%s\n' "$v"
  done | tail -n 1)

  curl -s -o /bin/unified_agent https://storage.yandexcloud.net/yc-unified-agent/releases/$ua_version/unified_agent
  chmod +x /bin/unified_agent
fi

systemctl enable unified_agent.service
systemctl start unified_agent.service --no-block
systemctl status unified_agent.service

