#!/usr/bin/env zsh

# Base functions for repo management. May be overridden by integrations scripts.

clone_repo() {
  if [ ! -d "../$1" ]; then
    git clone "git@github.com:theorchard/$1.git" "../$1"
  else
    echo "repo already exists, skipping: ../$1"
  fi
}

setup_repo() {
  _repo_exists "$1" || return 1

  local info="\nSetting up ../$1\n"
  cd ../$1

  # Copy local files if they don't already exist
  if [[ -f .env.shadow && ! -f .env ]]; then
    echo -e "$info\tcreating .env from .env.shadow"
    cp .env.shadow .env
  fi
  if [[ -f .split.shadow && ! -f .split ]]; then
    echo -e "$info\tcreating .split from .split.shadow"
    cp .split.shadow .split
  fi

  cd -
}

update_deps() {
  _repo_exists "$1" || return 1

  local info="\nUpdating dependencies for ../$1\n"
  cd ../$1

  if [ -f package.json ]; then
    echo -e "$info"
    yarn install
  elif [ -f pyproject.toml ]; then
    echo -e "$info"
    make dev_env
  else
    echo -e "\tno package.json or pyproject.toml found, skipping dependency installation"
  fi

  cd -
}

add_upstream() {
  _repo_exists "$1" || return 1

  cd ../$1

  if ! git remote -v | grep -q upstream; then
    echo -e "\nAdding upstream to ../$1\n"
    git remote add upstream git@github.com:theorchard/$1.git
  else
    echo "upstream remote already exists, skipping: ../$1"
  fi

  cd -
}

rebase_repo() {
  _repo_exists "$1" || return 1

  echo -e "\nRebasing ../$1\n"
  cd ../$1

  STASHED=false

  # if the workspace is dirty, stash uncommitted changes
  if [ -n "$(git status --porcelain)" ]; then
    echo -e "\tStashing changes in $1"
    git stash push -m "auto-stash before rebase_repo"
    STASHED=true
  fi

  # save the branch we were on and switch to master
  ORIGINAL_BRANCH=$(git branch --show-current)
  if [ "$ORIGINAL_BRANCH" != "master" ]; then
    git switch master
  fi

  git fetch upstream
  git rebase upstream/master

  # switch back to the branch we were on if it wasn't master
  if [ "$ORIGINAL_BRANCH" != "master" ]; then
    git switch "$ORIGINAL_BRANCH"
    git rebase master
  fi

  # restore previous uncommitted changes
  if [ "$STASHED" = true ]; then
    git stash pop
    echo -e "\tApplied stashed changes to $1 branch $ORIGINAL_BRANCH"
  fi

  cd -
}

_repo_exists() {
  if [ ! -d "../$1" ]; then
    echo "repo does not exist: ../$1. run clone_repos first."
    return 1
  fi
}
