#!/bin/bash

#############################################################
#### Grafana Mimir Install Script for Oracle Linux,      #### 
#### Centos/Redhat and Debian/Ubuntu Servers.            ####       
####                                                     ####
#### Author: Phil Connor 01/09/2025                      ####
#### License: MIT                                  ####
#### Contact: contact@mylinux.work                            ####
#### Version 1.00.010925                                 ####
####                                                     ####
#### To use this script chmod it to 755                  ####
#### or simply type bash <filename.sh>                   ####  
#############################################################

########################
### System Variables ###
########################
if [ "$(command -v lsb_release)" ]; then
    OS=$(lsb_release -i | awk '{print $3}' | tr '[:upper:]' '[:lower:]')
else
    OS=$(grep PRETTY_NAME /etc/os-release | sed 's/PRETTY_NAME=//g' | tr -d '="' | awk '{print $1}' | tr '[:upper:]' '[:lower:]')
fi

domain=mylinux.work
bindir=/usr/local/bin
mimirdir=/etc/prometheus
datadir=/mimir

if [ -d "/usr/lib/systemd/system" ]; then
    psdir='/etc/systemd/system'
else
    psdir='/usr/lib/systemd/system'
fi

#########################
### Check permissions ###
#########################
if [[ $EUID -ne 0 ]]; then
    echo ''
    echo "$(basename "$0") This script must be run as root! Login as root, or sudo/su." 
    echo ''
    exit 1
fi

######################
### Package Manager ##
######################
pkgmgr="yum -y"
if [ "$OS" = "ubuntu" ]; then
    pkgmgr="apt -y"
fi

#################################
#### Add Mimir User/Group ####
#################################
if ! grep mimir /etc/passwd; then 
    groupadd --system mimir
    if [ "$OS" = "ubuntu" ]; then
        useradd -s /sbin/nologin --system -g mimir mimir
    else
        useradd -m -s /bin/false mimir -g mimir
    fi
fi

#################################
#### Check for wget and curl #### 
#################################
if [ ! "$(command -v wget)" ]; then
    $pkgmgr install wget
fi

if [ ! "$(command -v curl)" ]; then
    $pkgmgr install curl
fi

if [ ! "$(command -v unzip)" ]; then
    $pkgmgr install unzip
fi

##########################
### Install Mimir ###
##########################
install_mimir() {
    {
        # Create base directories if they don't exist
        if [ ! -d "$mimirdir" ]; then
            mkdir -p $mimirdir || { echo "Failed to create $mimirdir directory"; exit 1; }
        fi
        
        if [ ! -d "$datadir" ]; then
            mkdir -p $datadir || { echo "Failed to create $datadir directory"; exit 1; }
        fi
        
        # Create Mimir subdirectories
        mkdir -p $datadir/{tsdb-sync,data/tsdb,mimir-tsdb,compactor,mimir-ruler}
        chown -R mimir:mimir $datadir
        
        # Download and install Mimir
        cd /tmp || exit 2
        echo "Downloading latest Grafana Mimir..."
        curl -s https://api.github.com/repos/grafana/mimir/releases/latest | grep browser_download_url | grep linux-amd64 | cut -d '"' -f 4 | wget -qi - || { echo "Failed to download Mimir"; exit 1; }
        
        tar -xvf mimir-linux-amd64.tar.gz
        mv mimir-linux-amd64 $bindir/mimir || exit 1
        chown mimir:mimir $bindir/mimir || exit 1
        rm -rf /tmp/mimir-linux-amd64.tar.gz
        
        # Get server IP address
        SERVER_IP=$(hostname -I | awk '{print $1}')
        
        # Create Mimir config
        touch $mimirdir/mimir.yml
        {
            echo '# Mimir Configuration - Single Instance Mode'
            echo 'multitenancy_enabled: false'
            echo ''
            echo 'blocks_storage:'
            echo '  backend: filesystem'
            echo '  bucket_store:'
            echo "    sync_dir: $datadir/tsdb-sync"
            echo '  filesystem:'
            echo "    dir: $datadir/data/tsdb"
            echo '  tsdb:'
            echo "    dir: $datadir/mimir-tsdb"
            echo '    retention_period: 720h'
            echo ''
            echo 'compactor:'
            echo "  data_dir: $datadir/compactor"
            echo '  sharding_ring:'
            echo '    kvstore:'
            echo '      store: inmemory'
            echo ''
            echo 'distributor:'
            echo '  ring:'
            echo '    kvstore:'
            echo '      store: inmemory'
            echo ''
            echo 'ingester:'
            echo '  ring:'
            echo '    kvstore:'
            echo '      store: inmemory'
            echo '    replication_factor: 1'
            echo ''
            echo 'ruler_storage:'
            echo '  backend: filesystem'
            echo '  filesystem:'
            echo "    dir: $datadir/mimir-ruler"
            echo ''
            echo 'server:'
            echo '  http_listen_port: 9009'
            echo '  log_level: info'
            echo ''
            echo 'memberlist:'
            echo '  abort_if_cluster_join_fails: false'
            echo '  bind_port: 7946'
            echo "  advertise_addr: $SERVER_IP"
            echo '  join_members: []'
            echo ''
            echo 'store_gateway:'
            echo '  sharding_ring:'
            echo '    replication_factor: 1'
            echo '    kvstore:'
            echo '      store: inmemory'
            echo ''
            echo 'limits:'
            echo '  max_global_series_per_user: 0'
            echo '  max_global_exemplars_per_user: 100000'
        } > $mimirdir/mimir.yml
        
        chown mimir:mimir $mimirdir/mimir.yml
        
        # Create systemd service
        {
            echo '[Unit]'
            echo 'Description=Grafana Mimir'
            echo 'Documentation=https://grafana.com/docs/mimir/'
            echo 'After=network-online.target'
            echo 'Wants=network-online.target'
            echo ''
            echo '[Service]'
            echo 'Type=simple'
            echo 'User=mimir'
            echo 'Group=mimir'
            echo "ExecStart=$bindir/mimir -config.file=$mimirdir/mimir.yml"
            echo "ExecReload=/bin/kill -HUP \$MAINPID"
            echo 'TimeoutStopSec=20s'
            echo 'SendSIGKILL=no'
            echo ''
            echo '# Output to journal'
            echo 'StandardOutput=journal'
            echo 'StandardError=journal'
            echo 'SyslogIdentifier=mimir'
            echo ''
            echo '# Restart'
            echo 'Restart=on-failure'
            echo 'RestartSec=5s'
            echo ''
            echo '# Security'
            echo 'NoNewPrivileges=yes'
            echo 'PrivateTmp=yes'
            echo 'ProtectSystem=full'
            echo 'ProtectHome=yes'
            echo "ReadWritePaths=$datadir"
            echo ''
            echo '# Resource limits'
            echo 'LimitNOFILE=1048576'
            echo 'LimitNPROC=1048576'
            echo ''
            echo '# Environment'
            echo 'Environment=GOMAXPROCS=4'
            echo ''
            echo '[Install]'
            echo 'WantedBy=multi-user.target'
        } > $psdir/mimir.service
        
        systemctl daemon-reload
        systemctl enable --now mimir
        
        echo ""
        echo "=========================================="
        echo "Mimir installation complete!"
        echo "=========================================="
        echo "Mimir UI: http://localhost:9009"
        echo "Config: $mimirdir/mimir.yml"
        echo "Data: $datadir"
        echo ""
        echo "Add to Prometheus remote_write:"
        echo "  remote_write:"
        echo "    - url: http://localhost:9009/api/v1/push"
        echo ""
    }
}

################################
### Install and Config Nginx ###
################################
install_nginx() {
    {
        $pkgmgr install nginx
        
        if [ -d "/etc/nginx/sites-available" ]; then
            sitesa=/etc/nginx/sites-available
            sitese=/etc/nginx/sites-enabled/
        elif [ -d "/etc/nginx/conf.d" ]; then
            sitesa=/etc/nginx/conf.d
        fi

        touch "$sitesa"/mimir.conf
        {
            echo 'server {'
            echo '    listen 80;'
            echo '    listen [::]:80;'
            echo ''    
            echo "    server_name mimir.$domain;"
            echo ''    
            echo '    location / {'
            echo '        proxy_pass http://localhost:9009/;'
            # shellcheck disable=SC2016
            echo '        proxy_set_header Host $host;'
            # shellcheck disable=SC2016
            echo '        proxy_set_header X-Real-IP $remote_addr;'
            # shellcheck disable=SC2016
            echo '        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;'
            # shellcheck disable=SC2016
            echo '        proxy_set_header X-Forwarded-Proto $scheme;'
            echo '        proxy_read_timeout 300s;'
            echo '        proxy_connect_timeout 75s;'
            echo '        }'
            echo '}'
        } > "$sitesa"/mimir.conf
        
        if [ -d "/etc/nginx/sites-available" ]; then
            ln -s "$sitesa"/mimir.conf "$sitese" 2>/dev/null || true
        fi

        if nginx -t; then
            systemctl restart nginx
            echo "Nginx configured for Mimir at mimir.$domain"
        else
            echo "Nginx configuration test failed"
        fi
    }
}

######################
### Function Calls ###
######################
install_mimir

# Uncomment to install nginx reverse proxy
# install_nginx

#############################################################

echo ""
echo "=========================================="
echo "Installation Summary"
echo "=========================================="
echo "Mimir version: $(mimir --version 2>&1 | head -1)"
echo "Status: $(systemctl is-active mimir)"
echo ""
echo "Check status: systemctl status mimir"
echo "View logs: journalctl -u mimir -f"
echo ""
