#!/bin/bash

DIRECTORY=$1
CURRENT_USER=$(logname)
WEB_USER=http

mkdir -p ${DIRECTORY}

echo Creating Project based from laravel/laravel.

composer create-project laravel/laravel ${DIRECTORY}

cd ${DIRECTORY}

echo Adding repos to composer.


repositories=("magicforger" "framework" "auth" "developer")
base_path="/srv/http/packages"

for repo in "${repositories[@]}"; do
  composer config repositories.wizard.$repo path $base_path/$repo
done

echo Setting base dependencies.

composer require --dev wizard/magicforger wizard/developer
composer require wizard/framework wizard/auth

echo Setting up packages

php artisan auth:install 
php artisan vendor:publish --provider="Wizard\\Framework\\FrameworkServiceProvider" --force
php artisan vendor:publish --provider="Wizard\Development\DevelopmentServiceProvider" --force


echo Running NPM.

npm install
npm install -D sass-embedded
npm run build


echo Removing all .gitignore files.

find . -type f -name ".gitignore" ! -path "./vendor/*" -delete


echo Setting file ownership and permissions.
touch storage/logs/laravel.log

sudo chown $CURRENT_USER:$WEB_USER -R ./*
sudo chown $CURRENT_USER:$WEB_USER -R ./.*
chmod 775 -R storage


# Make a mariadb for the app
DB_NAME="${DIRECTORY}"
DB_USER="${DB_NAME}_user"
DB_PASS="${DB_NAME}_pass"

# Create the database
sudo mariadb -u root -p -e "CREATE DATABASE ${DB_NAME};"

# Make a db user and password
sudo mariadb -u root -p -e "CREATE USER '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASS}';"
sudo mariadb -u root -p -e "GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'localhost';"
sudo mariadb -u root -p -e "FLUSH PRIVILEGES;"

# Update the .env for this info
sed -i "s/DB_CONNECTION=.*/DB_CONNECTION=mariadb/" .env
sed -i "s/# DB_/DB_/" .env
sed -i "s/DB_DATABASE=.*/DB_DATABASE=${DB_NAME}/" .env
sed -i "s/DB_USERNAME=.*/DB_USERNAME=${DB_USER}/" .env
sed -i "s/DB_PASSWORD=.*/DB_PASSWORD=${DB_PASS}/" .env
sed -i "s/SESSION_DRIVER=.*/SESSION_DRIVER=database/" .env
# Remove un-necessary variables
sed -i '/^REDIS_/d' .env
sed -i '/^AWS_/d' .env

php artisan config:clear
php artisan config:cache

php artisan migrate:fresh
hg init
hg addremove
hg commit -m"Initial Commit and package setup"
