#!/bin/bash
initdb() {
  postgresql-setup initdb
  cp /var/lib/awx/setup/pg_hba.conf /var/lib/pgsql/data/
  chmod a+r /var/lib/pgsql/data/pg_hba.conf
}

initredis() {
  cp /var/lib/awx/setup/redis.conf /etc/redis.conf
  chmod a+r /etc/redis.conf
}

initawx() {
  hostnamectl set-hostname awx
  awx-manage migrate --no-input
  if [ $? -ne 0 ]; then
    echo -e "\033[31m Migrate to postgresql failed \033[0m"
    echo -e "\033[31m Please check the database connection profile in /etc/tower/conf.d/credentials.py \033[0m"
  fi
  awx-manage createsuperuser --username=admin --email=admin@localhost --noinput
  if [ $? -ne 0 ]; then
    echo -e "\033[33m Awx has been initialized, no need to create a default user \033[0m"
  else
    awx-manage update_password --username=admin --password=admin
    awx-manage provision_instance --hostname=$(hostname)
    awx-manage register_queue --queuename=tower --instance_percent=100
    awx-manage create_preload_data
    awx-manage collectstatic --noinput --clear -v0
    echo 'from django.conf import settings; x = settings.AWX_TASK_ENV; x["HOME"] = "/var/lib/awx"; settings.AWX_TASK_ENV = x' | awx-manage shell
    chown -R awx:awx /var/log/tower/
    echo "Awx data initialization is complete"
  fi
}

initawx

