#!/bin/bash

KAZ_ROOT=$(cd $(dirname $0)/../..; pwd)
. "${KAZ_ROOT}/bin/.commonFunctions.sh"
setKazVars

cd $(dirname $0)
. "${DOCKERS_ENV}"
. "${KAZ_KEY_DIR}/env-${gitServName}"
. "${KAZ_KEY_DIR}/env-${gitDBName}"

GIT_URL="${httpProto}://${gitHost}.${domain}"

checkDockerRunning "${gitServName}" "Gitea" || exit

if ! grep -q  "INSTALL_LOCK\s*=\s*true" "${DOCK_LIB}/volumes/gitea_gitData/_data/gitea/conf/app.ini" 2>/dev/null ; then
    printKazMsg "\n  *** Premier lancement de GIT"

    waitUrl "${GIT_URL}"

    curl -X POST \
	 --data-urlencode "admin_confirm_passwd=${pass_admin}" \
	 --data-urlencode "admin_email=${admin_email}" \
	 --data-urlencode "admin_name=${user_admin}" \
	 --data-urlencode "admin_passwd=${pass_admin}" \
	 --data-urlencode "allow_only_external_registration=" \
	 --data-urlencode "app_name=Gitea: Git with a cup of tea" \
	 --data-urlencode "app_url=${httpProto}://${gitHost}.${domain}/" \
	 --data-urlencode "charset=utf8" \
	 --data-urlencode "db_host=db:3306" \
	 --data-urlencode "db_name=${MYSQL_DATABASE}" \
	 --data-urlencode "db_passwd=${MYSQL_PASSWORD}" \
	 --data-urlencode "db_schema=" \
	 --data-urlencode "db_path=/data/gitea/gitea.db" \
	 --data-urlencode "db_type=mysql" \
	 --data-urlencode "db_user=${MYSQL_USER}" \
	 --data-urlencode "default_allow_create_organization=on" \
	 --data-urlencode "default_enable_timetracking=on" \
	 --data-urlencode "default_keep_email_private=" \
	 --data-urlencode "disable_gravatar=" \
	 --data-urlencode "disable_registration=on" \
	 --data-urlencode "domain=${gitHost}.${domain}" \
	 --data-urlencode "enable_captcha=" \
	 --data-urlencode "enable_federated_avatar=on" \
	 --data-urlencode "enable_open_id_sign_in=" \
	 --data-urlencode "enable_open_id_sign_up=" \
	 --data-urlencode "http_port=3000" \
	 --data-urlencode "lfs_root_path=/data/git/lfs" \
	 --data-urlencode "log_root_path=/data/gitea/log" \
	 --data-urlencode "mail_notify=on" \
	 --data-urlencode "no_reply_address=noreply.localhost" \
	 --data-urlencode "offline_mode=" \
	 --data-urlencode "password_algorithm=pbkdf2" \
	 --data-urlencode "register_confirm=on" \
	 --data-urlencode "repo_root_path=/data/git/repositories" \
	 --data-urlencode "require_sign_in_view=" \
	 --data-urlencode "run_user=git" \
	 --data-urlencode "smtp_from=admin@${smtpHost}.${domain}" \
	 --data-urlencode "smtp_host=${smtpHost}.${domain}" \
	 --data-urlencode "smtp_passwd=" \
	 --data-urlencode "smtp_user=" \
	 --data-urlencode "ssh_port=2202" \
	 --data-urlencode "ssl_mode=disable" \
	 "${httpProto}://${gitHost}.${domain}/"

fi

# https://docs.gitea.io/en-us/customizing-gitea/
DATA_DIR="${DOCK_VOL}/gitea_gitData/_data/gitea"
mkdir -p "${DATA_DIR}/public/img"
cp "$(dirname $0)/logo.svg" "${DATA_DIR}/public/img/logo.svg"
chown -R 1000:1000 "${DATA_DIR}/public/"
