#!/usr/bin/env bash
set -e
VLOKI=$(
    curl -s "https://api.github.com/repos/grafana/loki/releases/latest" |
        grep -Po '"tag_name": "v\K[0-9.]+'
)
sudo mkdir -p /opt/loki
[[ -f /opt/loki/loki.zip ]] || sudo wget -O /opt/loki/loki.zip \
    "https://github.com/grafana/loki/releases/download/v${VLOKI}/loki-linux-amd64.zip"
[[ -f /opt/loki/promtail.zip ]] || sudo wget -O /opt/loki/promtail.zip \
    "https://github.com/grafana/loki/releases/download/v${VLOKI}/promtail-linux-amd64.zip"
sudo unzip /opt/loki/loki.zip -d /opt/loki
sudo unzip /opt/loki/promtail.zip -d /opt/loki
sudo ln -s /opt/loki/loki-linux-amd64 /usr/local/bin/loki
sudo ln -s /opt/loki/promtail-linux-amd64 /usr/local/bin/promtail
sudo wget -O /opt/loki/loki-local-config.yaml \
    "https://raw.githubusercontent.com/grafana/loki/v${VLOKI}/cmd/loki/loki-local-config.yaml"
cat <<EOF | sudo tee /opt/loki/promtail-local-config.yaml
server:
  http_listen_port: 9080
  grpc_listen_port: 0
positions:
  filename: /data/loki/positions.yaml
clients:
  - url: http://localhost:3100/loki/api/v1/push
scrape_configs:
  - job_name: system
    static_configs:
      - targets:
          - localhost
        labels:
          job: suricata_logs
          __path__: /var/log/suricata/eve.json
EOF
cat <<EOF | sudo tee /etc/systemd/system/loki.service
[Unit]
Description=Loki service
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/loki -config.file /opt/loki/loki-local-config.yaml

[Install]
WantedBy=multi-user.target
EOF
cat <<EOF | sudo tee /etc/systemd/system/promtail.service
[Unit]
Description=Promtail service
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/promtail -config.file /opt/loki/promtail-local-config.yaml

[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable loki.service
sudo systemctl enable promtail.service
