#!/bin/bash

set -e

die() { echo "$1"; exit 1; }

INSTALL_METHOD="install"
[[ -n "$1" ]] && INSTALL_METHOD="$1"

if [[ $INSTALL_METHOD = "update" ]]; then
    echo "Install method: UPDATE -- updates envsubst_update_files"
else
    echo "No option passed, assuming first boot case, copying all initial files."
fi

TIMUS_DIR="/opt/control.setloki"
SOURCE_DIR="${TIMUS_DIR}/source"
DEFAULTS_DIR="${SOURCE_DIR}/defaults"
TEMPLATES_DIR="${SOURCE_DIR}/templates"

# Check if env file exist
if [ ! -f /etc/timus/timus.env ]; then
    die "Error: No env file found"
fi

# Check if the script exists
if [ ! -e /etc/profile.d/timus.sh ]; then
    die "Error: No profile script found"
fi

source "/etc/profile.d/timus.sh"

[[ -v TP && -v DEPLOY_PREFIX && -v PRODUCT_DOMAIN && -v SERVICE_DOMAIN ]] \
    || die 'Missing env variables, make sure you have passed environment variables correctly'

echo "Setting up environment..."
echo "TP: $TP"
echo "DEPLOY_PREFIX: $DEPLOY_PREFIX"
echo "PRODUCT_DOMAIN: $PRODUCT_DOMAIN"
echo "SERVICE_DOMAIN: $SERVICE_DOMAIN"

mkdir -p ${DEFAULTS_DIR}
cp -r "$TEMPLATES_DIR/." "${DEFAULTS_DIR}/"

# Apply on first boots and updates
VARIABLES="\$TP \$DEPLOY_PREFIX \$PRODUCT_DOMAIN \$SERVICE_DOMAIN"

envsubst_files() {
    while read file_path || [ -n "$file_path" ]; do
        for file in $(find "${DEFAULTS_DIR}/$file_path" -type f); do
            cp --attributes-only --preserve "${file}" "${file}.tmp"
            envsubst "$VARIABLES" < "$file" > "${file}.tmp"
            mv "${file}.tmp" "${file}"
            # Copy update files to matching locations
            cp "${file}" "/${file_path}"
        done
    done < <(jq -r ".$1[]" $2)
}

# Update all files which are common to all environments
envsubst_files "common" "/opt/control.setloki/source/change_env/envsubst_update_files.json"

# Update all files which are staging only
if [[ "${DEPLOY_PREFIX}" =~ "-st" ]]; then
    envsubst_files "staging_only" "/opt/control.setloki/source/change_env/envsubst_update_files.json"
fi

# Apply only for first boot
if [[ $INSTALL_METHOD != "update" ]]; then
    # Install all files which are common to all environments
    envsubst_files "common" "/opt/control.setloki/source/change_env/envsubst_install_files.json"

    # Install all files which are staging only
    if [[ "${DEPLOY_PREFIX}" =~ "-st" ]]; then
        envsubst_files "staging_only" "/opt/control.setloki/source/change_env/envsubst_install_files.json"
    fi

    # Update hosts files
    echo "192.168.255.1 setup${DEPLOY_PREFIX}.${PRODUCT_DOMAIN}" >/etc/dnsmasq.hosts
    echo "192.168.255.1 setup${DEPLOY_PREFIX}.${PRODUCT_DOMAIN}" >>/etc/hosts

    # Get public key of new environment
    wget -O - "https://repo${DEPLOY_PREFIX}.${SERVICE_DOMAIN}/loki.public.gpg.key" | apt-key add - || die "Adding public key of ${DEPLOY_PREFIX} failed!"

    # Get up-to-date setup app certificate from server
    client_id="deployment-yMdpuJVklaH"
    client_secret="wiZ2Fmrw8qe7921r8UHX"
    post_data="{\"client_id\": \"${client_id}\", \"client_secret\": \"$client_secret\"}"
    auth_url="https://auth${DEPLOY_PREFIX}.${SERVICE_DOMAIN}"
    config_url="https://config${DEPLOY_PREFIX}.${SERVICE_DOMAIN}"
    token=$(curl -s --connect-timeout 30 --max-time 60 -X POST -H "Content-Type: application/json" -d "$post_data" "${auth_url}/node" | jq -r '.results.token' \
        || die "Fetch token from ${auth_url}/node failed!" )
    certs=$(curl -s --connect-timeout 30 --max-time 60 -X GET -H "Authorization: Bearer $token" "${config_url}/keys/common" \
        || die "Fetch certs from ${config_url}/keys/common failed!")
    echo "$certs" | jq -r '.results."fullchain.pem"' > $TIMUS_DIR/service/setup_app/ssl_cert/fullchain.pem
    echo "$certs" | jq -r '.results."privkey.pem"' > $TIMUS_DIR/service/setup_app/ssl_cert/privkey.pem
fi
