#!/bin/bash

set -eu

mkdir -p /app/data/storage

reset_root_password() {
    sleep 10

    while ! curl --fail http://localhost:9000/; do
        echo "==> (reset root password) Waiting for peertube to initialize..."
        sleep 5
    done

    echo "changeme" | npm run reset-password -- -u root
}

# cd /var/www/peertube/peertube-latest/scripts && sudo -H -u peertube ./upgrade.sh
if [[ ! -f "/app/data/production.yaml" ]]; then
    echo "==> First run. creating config"
    cp /app/pkg/production.yaml.example /app/data/production.yaml

    # this is sed because there are too many paths
    sed -e 's,/var/www/peertube/storage,/app/data/storage,g' -i /app/data/production.yaml

    reset_root_password &
fi

echo "==> Updating configs"
yq w -i /app/data/production.yaml webserver.hostname "${CLOUDRON_APP_DOMAIN}"

# database
yq w -i /app/data/production.yaml database.hostname "${CLOUDRON_POSTGRESQL_HOST}"
yq w -i /app/data/production.yaml database.port "${CLOUDRON_POSTGRESQL_PORT}"
yq w -i /app/data/production.yaml database.username "${CLOUDRON_POSTGRESQL_USERNAME}"
yq w -i /app/data/production.yaml database.password "${CLOUDRON_POSTGRESQL_PASSWORD}"
yq w -i /app/data/production.yaml database.name "${CLOUDRON_POSTGRESQL_DATABASE}"
yq d -i /app/data/production.yaml database.suffix

# redis
yq w -i /app/data/production.yaml redis.hostname "${CLOUDRON_REDIS_HOST}"
yq w -i /app/data/production.yaml redis.port "${CLOUDRON_REDIS_PORT}"
yq w -i /app/data/production.yaml redis.auth "${CLOUDRON_REDIS_PASSWORD}"

# smtp
yq w -i /app/data/production.yaml smtp.hostname "${CLOUDRON_MAIL_SMTP_SERVER}"
yq w -i /app/data/production.yaml smtp.port "${CLOUDRON_MAIL_SMTP_PORT}"
yq w -i /app/data/production.yaml smtp.username "${CLOUDRON_MAIL_SMTP_USERNAME}"
yq w -i /app/data/production.yaml smtp.password "${CLOUDRON_MAIL_SMTP_PASSWORD}"
yq w -i /app/data/production.yaml smtp.tls false
yq w -i /app/data/production.yaml smtp.disable_starttls true
yq w -i /app/data/production.yaml smtp.from_address "${CLOUDRON_MAIL_FROM}"

chown -R cloudron:cloudron /app/data

echo "==> Starting PeerTube"
exec gosu cloudron:cloudron npm start

