#!/bin/bash

# Flows
source "flows/base"
source "flows/release"

# 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
      echo -e "❌ ${RED}GITEA_TOKEN is not set and couldn't be retrieved from kubectl${RESET}" >&2
      exit 1
    fi
    export GITEA_TOKEN
  fi

  echo -e "💰 ${GREEN}Environment variables set${RESET}"
}

build() {
  # Create build directory if it doesn't exist
  mkdir -p "$PACKAGE_DIRECTORY"
  # Get version
  local version=$(get-version)
  echo -e "📦 ${CYAN}Building site version ${GREEN}v$version${RESET}..."
  # Create the tarball
  tar -czf "$PACKAGE_DIRECTORY/$GITEA_REPOSITORY.tar.gz" -C "$BUILD_DIRECTORY" .
  echo -e "✨ ${GREEN}Build complete${RESET}"
}

usage() {
  echo -e "    env            Load environment variables from .env file."
  echo -e "    build          Build the site (requires env)."
  echo -e "    tag            Tag the build (requires build)."
  echo -e "    package        Package the build (requires build)."
  echo -e "    release        Release the build (requires package)."
}

case "$1" in
  env) env;;
  build) env; build;;
  tag) env; tag;;
  package) env; package;;
  release) env; release;;
  *) base "$@";;
esac