#!/bin/bash
# Configure Elasticsearch for Odin
# 

echo -e "\e[93m"

log() {
    echo -e "\t\e[96m[*]${1}\e[93m"
}

export IP=$(ip route | awk '/src/{print $9}')
echo "elasticsearch" >/etc/hostname
echo -e "${IP}\telasticsearch" >> /etc/hosts

deluser -q --remove-home ubuntu

apt-get update || exit 1
apt-get --purge remove snapd lxd -y
apt-get upgrade -y
apt-get install -y htop wget default-jre python-pip

wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | apt-key add -
echo "deb https://artifacts.elastic.co/packages/5.x/apt stable main" >/etc/apt/sources.list.d/elastic-5.x.list
apt-get update
apt-get install elasticsearch -y
apt-get clean
pip install elasticsearch-curator

sed -i 's/#cluster.name: my-application/cluster.name: odin/g' /etc/elasticsearch/elasticsearch.yml
sed -i 's/#node.name: node-1/node.name: node-1/g' /etc/elasticsearch/elasticsearch.yml
sed -i "s/#network.host: 192.168.0.1/network.host: ${IP}/g" /etc/elasticsearch/elasticsearch.yml

mkdir /etc/curator/
cat >/etc/curator/delete_indices.yml <<EOF
---
actions:
  1:
    action: delete_indices
    description: >-
      Delete indices older than 30 days for odin- prefixed indices.
    options:
      ignore_empty_list: True
      timeout_override:
      continue_if_exception: False
      disable_action: False
    filters:
    - filtertype: pattern
      kind: prefix
      value: odin-
      exclude:
    - filtertype: age
      source: name
      direction: older
      timestring: '%Y.%m.%d'
      unit: days
      unit_count: 30
      exclude:
EOF

cat >/etc/curator/curator.yml<<EOF
---
client:
  hosts:
    - elasticsearch
  port: 9200
  url_prefix:
  use_ssl: False
  certificate:
  client_cert:
  client_key:
  ssl_no_validate: False
  http_auth:
  timeout: 30
  master_only: False

logging:
  loglevel: INFO
  logfile:
  logformat: default
  blacklist: ['elasticsearch', 'urllib3']
EOF

cat > /etc/cron.daily/curator <<EOF
#!/bin/bash
/usr/local/bin/curator /etc/curator/delete_index.yml --config /etc/curator/curator.yml
EOF
chmod +x /etc/cron.daily/curator

apt-get install -y prometheus-node-exporter

systemctl enable elasticsearch
systemctl start elasticsearch
echo -e "\e[0m"
