#!/bin/sh
set -eu

APP_ROOT="${APP_ROOT:-/app}"
DATA_ROOT="${MOBILEMODELS_DATA_ROOT:-/data}"

mkdir -p "$DATA_ROOT" "$DATA_ROOT/state"

sync_missing_dir_entries() {
  src_dir="$1"
  dst_dir="$2"

  mkdir -p "$dst_dir"

  for src_entry in "$src_dir"/*; do
    [ -e "$src_entry" ] || continue
    name="$(basename "$src_entry")"
    dst_entry="$dst_dir/$name"

    if [ -d "$src_entry" ]; then
      sync_missing_dir_entries "$src_entry" "$dst_entry"
      continue
    fi

    if [ ! -e "$dst_entry" ] && [ ! -L "$dst_entry" ]; then
      mkdir -p "$(dirname "$dst_entry")"
      cp -a "$src_entry" "$dst_entry"
    fi
  done
}

init_path() {
  rel_path="$1"
  src_path="$APP_ROOT/$rel_path"
  dst_path="$DATA_ROOT/$rel_path"

  if [ -d "$src_path" ]; then
    if [ ! -e "$dst_path" ] && [ ! -L "$dst_path" ]; then
      mkdir -p "$(dirname "$dst_path")"
      cp -a "$src_path" "$dst_path"
    else
      sync_missing_dir_entries "$src_path" "$dst_path"
    fi
  elif [ ! -e "$dst_path" ] && [ ! -L "$dst_path" ]; then
    mkdir -p "$(dirname "$dst_path")"
    cp -a "$src_path" "$dst_path"
  fi

  if [ -L "$src_path" ]; then
    current_target="$(readlink "$src_path" || true)"
    if [ "$current_target" = "$dst_path" ]; then
      return
    fi
    rm -f "$src_path"
  else
    rm -rf "$src_path"
  fi

  ln -s "$dst_path" "$src_path"
}

for rel_path in \
  workspace \
  dist
do
  init_path "$rel_path"
done
