script_path=$(dirname "$(readlink -f "$0")")

conf_file="Homestead.yaml"
env_file="backend/.env.example"
env_target="backend/.env"
default_host="api.repricev2.local"

echo Enter virtual host name \(by default api.repricev2.local\):
read project_host

if [ "$project_host" == "" ]; then
  project_host=$default_host
fi

function config_setup {
  echo Creating $conf_file...

  cp -p Homestead.yaml.example $conf_file
  sed -i 's:Path\\to\\project:'"$PWD"':' $conf_file

  if [ "$project_host" != "$default_host" ]; then
    sed -i 's:'"$default_host"':'"$project_host"':' $conf_file
  fi

  sleep 1
}

function add_host {
  echo Adding records to hosts...

  if grep -Fxq "$project_host" /etc/hosts
  then
      echo 192.168.10.10 $project_host | sudo tee -a /etc/hosts
  fi

  sleep 1
}

function env_setup {
  echo Creating .env file...

  cp -p $env_file $env_target
  sed -i 's:localhost:'"$project_host"':' $env_target

  sleep 1
}

function vagrant_setup {
  echo Building vagrant... This may take a time so feel free to go and get a coffee \;\)
  vagrant up

  echo Installing packages via composer...
  vagrant ssh -c "cd /home/vagrant/repricev2/backend && composer install"

  echo Executing artisan commands...
  vagrant ssh -c "php /home/vagrant/repricev2/backend/artisan key:generate"
  vagrant ssh -c "php /home/vagrant/repricev2/backend/artisan migrate"
  vagrant ssh -c "php /home/vagrant/repricev2/backend/artisan db:seed"

  echo All is set. If you are facing issues with starting vagrant just run \'vagrant destroy -f\' and \'vagrant up\' from project root
}

cd $script_path/../..

if [ ! -f "$conf_file" ]; then
  config_setup
  add_host
fi

if [ ! -f "$env_target" ]; then
  env_setup
fi

vagrant_setup

echo Now you can access backend at http://$project_host
sleep 1
echo Hit ENTER to exit...
read prompt
exit
