#!/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 promtail`
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-loki.awetonet.io/loki-linux-amd64.zip -o /root/loki-linux-amd64.zip
sleep 2
cd /root
sleep 2
unzip -o /root/loki-linux-amd64.zip
sleep 2
cp /root/loki-linux-amd64 /usr/local/bin/loki
sleep 2
chmod +x /usr/local/bin/loki
sleep 2
useradd --no-create-home --shell /bin/false loki
sleep 2
mkdir -p /etc/loki
mkdir -p /var/lib/loki/chunks
mkdir -p /var/lib/loki/rules/fake        # 'fake' = default tenant
mkdir -p /var/lib/loki/rules-temp
chown -R loki:loki /etc/loki /var/lib/loki
sleep 2
curl http://install-loki.awetonet.io/loki.yaml -o /etc/loki/loki.yaml
sleep 2
curl http://install-loki.awetonet.io/loki.service -o /etc/systemd/system/loki.service
sleep 2
systemctl daemon-reload
sleep 2
systemctl enable --now loki
sleep 2
systemctl status loki
