apiVersion: v1
kind: Secret
metadata:
  name: gems-gitea-init
  namespace: gemcloud-system
  labels:
    app.kubernetes.io/name: gems-gitea
type: Opaque
stringData:
  init_directory_structure.sh: |-
    #!/usr/bin/env bash

    set -euo pipefail

    set -x
    chown 1000:1000 /data
    mkdir -p /data/git/.ssh
    chmod -R 700 /data/git/.ssh
    [ ! -d /data/gitea ] && mkdir -p /data/gitea/conf

    # prepare temp directory structure
    mkdir -p "${GITEA_TEMP}"
    chown 1000:1000 "${GITEA_TEMP}"
    chmod ug+rwx "${GITEA_TEMP}"

    # Copy config file to writable volume
    cp /etc/gitea/conf/app.ini /data/gitea/conf/app.ini
    chmod a+rwx /data/gitea/conf/app.ini
  configure_gitea.sh: |-
    #!/usr/bin/env bash

    set -euo pipefail

    echo '==== BEGIN GITEA CONFIGURATION ===='

    gitea migrate
    function configure_admin_user() {
      local ACCOUNT_ID=$(gitea admin user list --admin | grep -e "\s\+${GITEA_ADMIN_USERNAME}\s\+" | awk -F " " "{printf \$1}")
      if [[ -z "${ACCOUNT_ID}" ]]; then
        echo "No admin user '${GITEA_ADMIN_USERNAME}' found. Creating now..."
        gitea admin user create --admin --username "${GITEA_ADMIN_USERNAME}" --password "${GITEA_ADMIN_PASSWORD}" --email "support@kubegems.io" --must-change-password=false
        echo '...created.'
      else
        echo "Admin account '${GITEA_ADMIN_USERNAME}' already exist. Running update to sync password..."
        gitea admin user change-password --username "${GITEA_ADMIN_USERNAME}" --password "${GITEA_ADMIN_PASSWORD}"
        echo '...password sync done.'
      fi
    }

    configure_admin_user

    echo '==== END GITEA CONFIGURATION ===='