#!/bin/bash

# Flows
source ./flows/base
source ./flows/git
source ./flows/packaging

# Vars
BUILD_DIRECTORY="web"
GITEA_ORGANIZATION="agreego"
GITEA_REPOSITORY="site"

env() {
  # Check if GITEA_TOKEN is set
  if [ -z "$GITEA_TOKEN" ]; then
    # If not set, try to get it from kubectl
    GITEA_TOKEN=$(kubectl get secret -n cellular gitea-git -o jsonpath='{.data.token}' | base64 --decode)
    if [ -z "$GITEA_TOKEN" ]; then
      error "GITEA_TOKEN is not set and couldn't be retrieved from kubectl" >&2
      return 2 # Handled error
    fi
    export GITEA_TOKEN
  fi

  success "Environment variables set"
}

build() {
  # Create build directory if it doesn't exist
  mkdir -p "$PACKAGE_DIRECTORY"
  # Get version
  local version
  version=$(get-version) || return $?
  info "Building site version v$version..."
  # Create the tarball
  tar -czf "$PACKAGE_DIRECTORY/$GITEA_REPOSITORY.tar.gz" -C "$BUILD_DIRECTORY" . || return 2
  success "Build complete"
}

site-usage() {
  printf "env\tLoad environment variables from .env file.\n"
  printf "build\tBuild the site.\n"
}

site-flow() {
  case "$1" in
    env) env; return $?;;
    build) build; return $?;;
    *) return 1 ;;
  esac
}

register-flow "site-flow" "site-usage"
dispatch "$@"