#!/bin/bash

green=`tput setaf 2`
reset=`tput sgr0`
os=$(awk -F= '$1=="ID" { print $2 ;}' /etc/os-release);
if [ $os != "\"centos\"" ]; then
    echo "The script works with centos only.. proceed with manual installation."
    exit;
    fi

sudo yum update -y;

if [ ! -f $HOME/.ssh/id_rsa.pub ]; then
    ssh-keygen
    fi
echo "";
echo "Add the following key under SSH keys in Gitlab";
echo ${green}
cat $HOME/.ssh/id_rsa.pub;
echo ${reset}
read -p "Add the key and press enter to continue";

sudo yum install git zip unzip -y

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash
source $HOME/.bashrc
nvm install 12;
nvm use 12;

curl --silent --location https://dl.yarnpkg.com/rpm/yarn.repo | sudo tee /etc/yum.repos.d/yarn.repo
sudo rpm --import https://dl.yarnpkg.com/rpm/pubkey.gpg
sudo yum install yarn

sudo yum install epel-release yum-utils -y;
yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm;
sudo yum-config-manager --enable remi-php74;
sudo yum install php php-common php-opcache php-mcrypt php-cli php-gd php-curl php-mysql php-ldap php-dom php-mbstring php-xml php-pdo php-openssl -y;

curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

if [ ! -f /data/cms ]; then
    git clone https://git.amrita.edu/cms/cms.git /data
    cd /data/cms
    chown -R cms:web .
	echo "Project located. Configuring and installing dependencies."
	chmod -R 0777 storage
	chmod -R 0777 bootstrap/cache
	cp .env.example .env
    echo "Opening env file. Update env and writequit the editor for changes to reflect".
    read -p "press enter to open the file"
    vim .env
    composer install;
	php artisan setup:environment;
	npm install --loglevel http;
	npm install -g gulp --loglevel http;
	echo "Minifying and packaging public assets"
	gulp --production;
    php artisan key:generate
	echo -n "Would you like to setup the database schema and seeds (y/n)? "
    read answer
    if echo "$answer" | grep -iq "^y" ;then
        php artisan migrate:reset
        php artisan migrate --seed
    else
        echo -n "Database setup cancelled. You should manually setup database and seeds if required."
    fi
    touch public/setup/setup_can_start.now
    info=`php artisan setup:show-info`
fi
git remote set-url origin git@git.amrita.edu:cms/cms.git;
path=`pwd`
echo "CMS has been download and the dependencies have been installed at $path";
echo $info;
