#!/bin/bash

timedatectl set-timezone Europe/Madrid

start_time=`date`
  
echo "provisioning started: ${start_time}" 

INSTALLER_ARCHIVE_NAME=elasticsearch-${ELASTICSEARCH_VERSION}.deb

NETWORK_INTERFACE=eth0

hostnamectl set-hostname ${MACHINE_HOSTNAME}

# Print some information about the container OS
hostnamectl

# Print some information about the container timezone
timedatectl

#####################################################################
## Get the IP address into an environment variable. This command outputs 
## an empty variable if the network interface name is not ${NETWORK_INTERFACE}
#####################################################################
ip_address=`ip -4 addr show ${NETWORK_INTERFACE} | grep -oP '(?<=inet\s)\d+(\.\d+){3}'`

dpkg --install /vagrant/artifacts/elasticsearch-${ELASTICSEARCH_VERSION}-amd64.deb

cp /vagrant/artifacts/memory.options /etc/elasticsearch/jvm.options.d/memory.options

cp /vagrant/artifacts/elasticsearch.yml /etc/elasticsearch/elasticsearch.yml

apt update

apt install -y curl mkcert

export CAROOT=/vagrant/artifacts/

mkcert -install

mkcert  --cert-file /etc/elasticsearch/certs/"${MACHINE_HOSTNAME}".pem --key-file /etc/elasticsearch/certs/"${MACHINE_HOSTNAME}"-key.pem "${MACHINE_HOSTNAME}"

KEYSTORE_PWD=123

## Reference: https://www.elastic.co/guide/en/elasticsearch/reference/current/security-basic-setup-https.html

openssl pkcs12 -export -out /etc/elasticsearch/certs/http.p12 -in /etc/elasticsearch/certs/"${MACHINE_HOSTNAME}".pem -inkey /etc/elasticsearch/certs/"${MACHINE_HOSTNAME}"-key.pem -passout pass:${KEYSTORE_PWD}

echo "${KEYSTORE_PWD}" | /usr/share/elasticsearch/bin/elasticsearch-keystore add xpack.security.transport.ssl.keystore.secure_password --stdin --force

echo "${KEYSTORE_PWD}" | /usr/share/elasticsearch/bin/elasticsearch-keystore add xpack.security.http.ssl.keystore.secure_password --stdin --force



source_str="#MACHINE_HOSTNAME#"
 
target_str="${MACHINE_HOSTNAME}"

sed -i "s/$source_str/$target_str/g" /etc/elasticsearch/elasticsearch.yml

systemctl daemon-reload

systemctl enable elasticsearch.service

systemctl start elasticsearch.service

systemctl status elasticsearch.service

elastic_password=`/usr/share/elasticsearch/bin/elasticsearch-reset-password --url https://${MACHINE_HOSTNAME}:9200 --username elastic --batch --silent --force`

echo "automatically generated password for user elastic: ${elastic_password}"

curl -X GET "https://elastic:${elastic_password}@${MACHINE_HOSTNAME}:9200/?pretty"

end_time=`date`

echo "This container has IP (interface: ${NETWORK_INTERFACE}): ${ip_address}"

echo "If you add this IP to the hostname (${MACHINE_HOSTNAME}) in your hosts file or you configure the LXD nameserver,"

echo "you can validate ElasticSearch connectivity with: curl -X GET https://elastic:${elastic_password}@${MACHINE_HOSTNAME}:9200/?pretty"

echo "provisioning started: ${start_time}" 
 
echo "provisioning ended: ${end_time}"
