#!/bin/bash

function truncateCurrentDirectory {
  if [[ -f ".env" ]]; then
    export $(cat .env | xargs) > /dev/null 2>&1
  fi
  rm .* > /dev/null 2>&1
}

function restoreEnvFile {
  if [[ -n ${PHP_VERSION} ]]; then
    echo "PHP_VERSION=${PHP_VERSION}" >>.env
  fi
  if [[ -n ${COMPOSE_PROJECT_NAME} ]]; then
    echo "COMPOSE_PROJECT_NAME=${COMPOSE_PROJECT_NAME}" >>.env
  fi
  if [[ -f ".env" ]]; then
    env -i $(cat .env | xargs) >.env
  fi
}

function create {
  truncateCurrentDirectory
  composer create-project ${PROJECT} . --no-interaction
  restoreEnvFile
}

EXISTING=$(ls -1)
if [[ ! -n "$EXISTING" ]]; then
  echo "Lets start a new project here ..."
  echo ""
  echo "Options to start:"
  echo "    0   none: start with an empty container"
  echo "    1   LakeDrops Drupal 8 project template"
  echo "    2   Drupal's community project template"
  echo "    3   Existing git repository"
  echo ""
  echo ""

  while true; do
      read -p "Choose an option: " OPTION
      case ${OPTION} in
          0 )
            break
            ;;

          1 )
            PROJECT="lakedrops/d8-project"
            create
            break
            ;;

          2 )
            PROJECT="drupal-composer/drupal-project:8.x-dev"
            create
            break
            ;;

          3 )
            read -p "Repository URL: " REPOSITORY
            if [[ -n "${REPOSITORY}" ]]; then
              truncateCurrentDirectory
              git clone ${REPOSITORY} .
              composer update
              restoreEnvFile
              break
            fi
            ;;

          * )
            echo "Please try again."
            ;;
      esac
  done
fi

restoreEnvFile
if [[ -x "${USERSHELL}" ]]; then
  ${USERSHELL}
else
  /usr/bin/fish
fi