#! /bin/bash

# This script is Benjamín C. Calderón's brain child (@benjcal).
# Written by Bo and a "good enough for now" draft.
#
# This script isn't safe to update between releases. The new_post_download script should be edited instead.

if [ -z $1 ]
  then
	echo "Please provide application (folder) name. i.e:"
	echo "bash <(curl -s https://raw.githubusercontent.com/boazsegev/facil.io/stable/scripts/new) hello_world"
  exit 0
fi

if [ -a $1 ]; then echo "Couldn't create folder, already exists?"; exit 1; fi
if [ -d $1 ]; then echo "Couldn't create folder, already exists?"; exit 1; fi

echo "Creating $1"
mkdir $1
cd $1

if [[ -z "${FIO_BRANCH}" ]]; then
  FIO_URL=$(curl -s https://api.github.com/repos/boazsegev/facil.io/releases/latest | grep tarball_url | cut -d '"' -f 4)
else
  FIO_URL=https://github.com/boazsegev/facil.io/archive/${FIO_BRANCH}.tar.gz
fi

echo $FIO_URL

# Was: curl -s -LJO https://github.com/boazsegev/facil.io/archive/stable.tar.gz
# But it's better to use releases than the stable branch:
curl -s -o facil.io.tar.gz -LJO $FIO_URL

if [ $? -ne 0 ]; then echo "Couldn't download the latest release from facil.io's GitHub repo."; exit 1; fi

tar --strip-components=1 -xzf facil.io.tar.gz
if [ $? -ne 0 ]; then echo "Couldn't extract tar."; exit 1; fi

rm facil.io.tar.gz
./scripts/new/cleanup
