#!/bin/bash

if [ `whoami` == root ]; then
  echo "Good you are root."
else
  echo "ERROR: Please become root first."
  echo "^^^^^^^^^^ SCRIPT ABORTED ^^^^^^^^^^"
  echo ""
  echo "Please type: sudo su"
  exit 0
fi

OS=`cat /etc/issue | awk '{print $1}' | head -n 1`
echo ""
echo "Detected OS: $OS"

# Validasi OS harus Debian atau Ubuntu
if [[ "$OS" == "Debian" || "$OS" == "Ubuntu" ]]; then
  echo "OS supported, continuing..."
else
  echo "ERROR: Unsupported OS - '$OS'"
  echo "^^^^^^^^^^ SCRIPT ABORTED ^^^^^^^^^^"
  echo "This script only supports Debian or Ubuntu."
  exit 1
fi

LOKI=`which loki`
if ! [ -z $LOKI ]; then
   echo ""
   echo "Loki installed already"
   /usr/local/bin/loki --version
   exit 0
fi

CURL=`which curl`
if [ -z $CURL ]; then
   apt-get install curl -y
fi

ZIP=`which unzip`
if [ -z $ZIP ]; then
   apt-get install zip -y
fi

curl http://install-promtail.awetonet.io/loki-linux-amd64.zip -o /root/loki-linux-amd64.zip
sleep 2
cd /root
unzip -o /root/loki-linux-amd64.zip
cp /root/loki-linux-amd64 /usr/local/bin/loki
chmod +x /usr/local/bin/loki
mkdir -p /etc/loki
curl http://install-loki.awetonet.io/loki-config.yaml -o /etc/loki/loki-config.yaml
mkdir -p /var/loki/{chunks,rules,compactor}
useradd --system --no-create-home loki
chown -R loki:loki /var/loki /etc/loki
curl http://install-loki.awetonet.io/loki.service -o /etc/systemd/system/loki.service
sleep 2
systemctl daemon-reload
systemctl enable --now loki
systemctl status loki
