#!/bin/bash

[[ -f /etc/update-motd.d/91-cloudron-install-in-progress ]] && exit

printf "**********************************************************************\n\n"

readonly cache_file4="/var/cache/cloudron-motd-cache4"
readonly cache_file6="/var/cache/cloudron-motd-cache6"

url4=""
url6=""
fallbackUrl=""

function detectIp() {
    if [[ ! -f "${cache_file4}" ]]; then
        ip4=$(curl -s --fail --connect-timeout 2 --max-time 2 https://ipv4.api.cloudron.io/api/v1/helper/public_ip | sed -n -e 's/.*"ip": "\(.*\)"/\1/p' || true)
        [[ -n "${ip4}" ]] && echo "${ip4}" > "${cache_file4}"
    else
        ip4=$(cat "${cache_file4}")
    fi

    if [[ ! -f "${cache_file6}" ]]; then
        ip6=$(curl -s --fail --connect-timeout 2 --max-time 2 https://ipv6.api.cloudron.io/api/v1/helper/public_ip | sed -n -e 's/.*"ip": "\(.*\)"/\1/p' || true)
        [[ -n "${ip6}" ]] && echo "${ip6}" > "${cache_file6}"
    else
        ip6=$(cat "${cache_file6}")
    fi

    [[ -n "${ip4}" ]] && url4="https://${ip4}"
    [[ -n "${ip6}" ]] && url6="https://[${ip6}]"
    [[ -z "${ip4}" && -z "${ip6}" ]] && fallbackUrl="https://<IP>"
}

if [[ -z "$(ls -A /home/yellowtent/platformdata/addons/mail/dkim)" ]]; then
    detectIp

    printf "\t\t\tWELCOME TO CLOUDRON\n"
    printf "\t\t\t-------------------\n"

    printf '\n\e[1;32m%-6s\e[m\n' "Visit one of the following URLs and accept the self-signed certificate to finish setup."
    [[ -n "${url4}" ]] && printf '\e[1;32m%-6s\e[m\n' "  * ${url4}"
    [[ -n "${url6}" ]] && printf '\e[1;32m%-6s\e[m\n' "  * ${url6}"
    [[ -n "${fallbackUrl}" ]] && printf '\e[1;32m%-6s\e[m\n' "  * ${fallbackUrl}"
    printf "\nCloudron overview - https://docs.cloudron.io/ \n"
    printf "Cloudron setup - https://docs.cloudron.io/installation/#setup \n"
else
    printf "\t\t\tNOTE TO CLOUDRON ADMINS\n"
    printf "\t\t\t-----------------------\n"
    printf "Please do not run apt upgrade manually as it will update packages that\n"
    printf "Cloudron relies on and may break the installation. Ubuntu security\n"
    printf "updates are automatically installed on this server every night.\n"
    printf "\n"
    printf "Read more at https://docs.cloudron.io/security/#os-updates\n"
    printf "\n"
    printf "Unable to reach the dashboard? Run 'cloudron-support --troubleshoot'.\n"
    printf "See https://docs.cloudron.io/troubleshooting/\n"
fi

printf "\nFor help and more information, visit https://forum.cloudron.io\n\n"

printf "**********************************************************************\n"
