#!/bin/bash

export LVALERT_OVERSEER_RESOURCE=${LVALERT_USER}_overseer_$(python3  -c 'import uuid; print(uuid.uuid4().hex)')

# Change the file permissions and ownership on /app/db_data:
chown gracedb:www-data /app/db_data
chmod 755 /app/db_data

## PGA: 2019-10-15: use certs from secrets for Shibboleth SP
SHIB_SP_CERT=/run/secrets/saml_certificate
SHIB_SP_KEY=/run/secrets/saml_private_key
if [[ -f $SHIB_SP_CERT && -f $SHIB_SP_KEY ]]
then
        echo "Using Shibboleth Cert from docker secrets over the image one"
        cp -f $SHIB_SP_CERT /etc/shibboleth/sp-cert.pem
        cp -f $SHIB_SP_KEY /etc/shibboleth/sp-key.pem
        chown _shibd:_shibd /etc/shibboleth/sp-{cert,key}.pem
        chmod 0600 /etc/shibboleth/sp-key.pem
fi

## PGA 2019-10-16: use secrets for sensitive environment variables
LIST="aws_ses_access_key_id
  aws_ses_secret_access_key
  django_db_password
  django_secret_key
  django_twilio_account_sid
  django_twilio_auth_token
  lvalert_password
  igwn_alert_password
  gracedb_ldap_keytab
  egad_url
  egad_api_key
  django_sentry_dsn"

for SECRET in $LIST
do
        VARNAME=$( tr [:lower:] [:upper:] <<<$SECRET)
        [  -f /run/secrets/$SECRET ] && export $VARNAME="$(< /run/secrets/$SECRET)"
done

# get x509 cert for ldap access from environment variable. 
echo "${GRACEDB_LDAP_KEYTAB}" | base64 -d | install -m 0600 /dev/stdin keytab
kinit ldap/gracedb.ligo.org@LIGO.ORG -k -t keytab

exec "$@"