#!/bin/bash

if [ `whoami` == root ]; then
  echo "Good you are root."
else
  echo "SUDO_REQUIRED"  
  exit 1                
fi

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

if [[ "$OS" == "Debian" || "$OS" == "Ubuntu" ]]; then
  echo "OS supported, continuing..."
else
  echo "ERROR: Unsupported OS - '$OS'"
  echo "^^^^^^^^^^ SCRIPT ABORTED ^^^^^^^^^^"
  exit 1
fi

# -- Install binary kalau belum ada --------------------
PROMTAIL=`which promtail`
if [ -z $PROMTAIL ]; then
    echo "Installing Promtail..."

    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/promtail-linux-amd64.zip -o /root/promtail-linux-amd64.zip
    sleep 2
    cd /root
    unzip -o /root/promtail-linux-amd64.zip
    sleep 2
    cp /root/promtail-linux-amd64 /usr/local/bin/promtail
    sleep 2
    echo "Binary installed."
else
    echo "Promtail binary already exists: $PROMTAIL"
    /usr/local/bin/promtail --version
fi

# -- Setup config & service (selalu dijalankan) --------
echo "Setting up config and service..."

curl http://install-promtail.awetonet.io/promtail-local-config.yaml \
    -o /etc/promtail-local-config.yaml
sleep 2

curl http://install-promtail.awetonet.io/promtail.service \
    -o /etc/systemd/system/promtail.service
sleep 2

systemctl daemon-reload
sleep 2
systemctl enable promtail
sleep 2

# -- Start service ------------------------------------
systemctl start promtail
sleep 2

if systemctl is-active --quiet promtail; then
    echo "Promtail service started successfully"
else
    echo "WARNING: Service failed to start - check config"
fi
