#!/bin/sh
set -e

# If number of arguments not equal to two
if [ $# -ne 2 ] ; then
  echo "invalid argument"
  exit 1
fi

DOT_ENV_FILE="$1"
FUNCTION_TO_CALL="$2"

alpine_source() {
  find "$CACHE_DIR" -name "$RELEASE_BASENAME.tar.gz" -type f | grep -q . || \
  wget "$ALPINE_MIRROR/$RELEASE_VERSION/releases/$ALPINE_ARCH/$RELEASE_BASENAME.tar.gz" -O "$CACHE_DIR/$RELEASE_BASENAME.tar.gz"

  mkdir -p "$CACHE_DIR/$RELEASE_BASENAME"

  find "$CACHE_DIR" -name "$RELEASE_BASENAME" -type d -empty -exec \
  tar --directory "$CACHE_DIR/$RELEASE_BASENAME" --extract --gzip --same-permissions --strip 1 --file="$CACHE_DIR/$RELEASE_BASENAME.tar.gz" \;
}

tailspin_bin() {
  find "$CACHE_DIR" -name tailspin.tar.gz -type f | grep -q . || \
  wget https://github.com/bensadeh/tailspin/releases/download/4.0.0/tailspin-aarch64-unknown-linux-musl.tar.gz -O "$CACHE_DIR/tailspin.tar.gz"

  mkdir -p "$CACHE_DIR/tailspin"

  find "$CACHE_DIR/tailspin" -type d -empty -exec tar xz -f "$CACHE_DIR/tailspin.tar.gz" -C "$CACHE_DIR/tailspin" \;
}

# Private function names start with underscore
_init() {
  . "$DOT_ENV_FILE"

  mkdir -p "$CACHE_DIR/aport"
  mkdir -p "$CACHE_DIR/extras"
  mkdir -p secrets
}

# Second argument is supposed to be name of one of the functions declared above
# functions starting with underscore are ignored (considered private)
FUNCTIONS=$(cat "$0" | awk '/\(\) {/ {print $1}' | rev | cut -c3- | rev | grep "^[^_]")
FOUND_FN=0
for FN in $FUNCTIONS; do
  if [ "$FN" = "$FUNCTION_TO_CALL" ]; then
    FOUND_FN=1
  fi
done

if [ $FOUND_FN -eq 1 ]; then
  _init

  echo "Calling $FUNCTION_TO_CALL"
  $FUNCTION_TO_CALL
else
  echo "invalid argument"
  exit 1
fi
