######################################################
## AUTHOR : HH                                      ##
## VER : 3.1.1 - 2019-01-14 12:04:00                ##
##                                                  ##
## DO NOT DISTRIBUTE - STRICTLY PROHIBITTED !!      ##
## COPY or DISTRIBUTE WILL AGAINST THE LAW          ##
######################################################

#!/bin/sh
RED=$(tput setaf 1)
NC=$(tput sgr0) # No Color
GR=$(tput setaf 2)
BL=$(tput setaf 4) 
WH=$(tput setaf 7)

bold=$(tput bold)
normal=$(tput sgr0)
blink=$(tput blin)

now=$(date)
#uncomment this for localhost installation using MAMP 
#mysql=/Applications/MAMP/Library/bin/mysql

#Use this for cpanel server
mysql=mysql

#GIT REPO URL BASE, change 'kuink' to general account -- keep slash on the end
#GIT=https://kuink@bitbucket.org/ngcID/ 



echo "                                     __  __ " 
echo "   ____  _____ ________  ____ ______/ /_/ /_ "
echo "  / __ \/ __  / ___/ _ \/ __ / ___/  __/ __ \ "
echo " / / / / /_/ / /__/  __/ /_/ / /  / /_/ / / / "
echo "/_/ /_/\__, /\___/\___/\__,_/_/   \__/_/ /_/  "
echo "      /____/                                " 

echo ${GR}== THIS IS THE INSTALLATION SCRIPT == 
echo == NGC Earth System ==
echo == Ver 1.0 HH : 2020-02-05 18:50:52 == ${NC}
echo 

## Eye candy progress bar
echo ${BL}${bold}Initiating installation sequence '..\n'
sleep 1
echo ${BL}${bold}Initiating installation sequence '....\n'
echo ${NC} 
## end of eye candy


sleep 1
echo ${WH}"Step 1 -> Please input your bitbucket userID !" ${NC}
read -p 'BitBucket UserID: ' userid
echo

sleep 1
echo ${WH}"Step 1.1 -> Please input the project repository URLthat you wish to deploy! only reponame.git" ${NC}
read -p 'Project Repo: ' project_repo
echo

sleep 1
echo ${WH}"Step 2 -> Please input the project folder that you wish to deploy!" ${NC}
read -p 'Project folder: ' folder
echo

PRO_URL=https://${userid}@bitbucket.org/ngcID/${project_repo}
CORE_URL=https://${userid}@bitbucket.org/ngcID/ngc-core.git

GITOPTION='-b develop —-single-branch'

echo ${BL}"Installing ${GR}NGC EARTH PROJECT${BL}, please wait ..."${NC}

#cloning from repo
echo ${GITOPTION} ${PRO_URL} ${folder}
git clone -b develop --single-branch ${PRO_URL} ${folder} || { echo >&2 ${RED}"Cloning failed with $?, exiting now!..."${NC}; exit 1; }

echo ${GR} "Step 2, Done!" ${NC}

echo 

#change directory to target folder
cd ${folder}
echo '... current directory =>' ${PWD}

echo

sleep 1
echo ${WH} "Step 3 -> Running Composer Update" ${NC}

#run Composer install
composer install

echo 
sleep 1
echo ${GR} "Step 3, Done!" ${NC}

echo
echo ${WH}"Step 4 -> Configuring config file ... " ${NC}

echo 
echo ${WH} "Generating .env file ..." ${NC}

#create .env file by copying the env.example to .env 
cp .env.example .env

echo
#echo '... update remote url for core and origin'

#set remote for ngc-core update/pull
# git remote add core ${CORE_URL}

# #disable push to core..
# git remote set-url --push core no_push

#disable push to project repo.. 
#don't allow user on project server to able push to repo
git remote set-url --push origin no_push

#rename url remote to support as support need 
#to pull it not by the programmers.

echo ${GR} "Step 4, Done!" ${NC}

echo
sleep 1
echo ${WH} "Step 5 -> Modify the permission of the storage folder" ${NC}

#update the folder permission
chmod -R 775 storage
chmod -R 775 bootstrap/cache

#add folder data on storage/framework/cache
#to be able to run php artisan cache:clear
mkdir storage/framework/cache/data


echo
sleep 1
#echo ${WH} "Clean up the working tree ..." ${NC}

#git add -A
#git commit -m "Fresh deployment on ${now} + composer update, ** this commit for local only" 

echo ${GR} "Step 5, Done!" ${NC}

#rename remote name
#git remote rename subrepo/public/ngc-cms ngc-cms
echo 

echo ${WH} "Step 6 -> Database Setup" ${NC}

# echo 
read -p 'Please input domain name/URL (without http://):' DOMAIN_NAME
read -p 'Please input database name :' MAINDB
read -p 'Please input database username :' USER_NAME
read -p 'Please input database password :' PASSWDDB

# echo ${BL} "Creating database and user" ${NC}
# echo 
# read -p 'Please input domain name/URL:' DOMAIN_NAME
# read -p 'Please input cPanel username :' USER_NAME

# # create random password
# PASSWDDB=$(cat /dev/random | LC_CTYPE=C tr -dc "[:alpha:]" | head -c 8)

# # replace "-" with "_" for database username
# MAINDB=${USER_NAME}'_ngcearth'

# # If /root/.my.cnf exists then it won't ask for root password
# if [ -f /root/.my.cnf ]; then

#     ${mysql} -e "CREATE DATABASE ${MAINDB} /*\!40100 DEFAULT CHARACTER SET utf8 */;"
#     ${mysql} -e "CREATE USER ${MAINDB}@localhost IDENTIFIED BY '${PASSWDDB}';"
#     ${mysql} -e "GRANT ALL PRIVILEGES ON ${MAINDB}.* TO '${MAINDB}'@'localhost';"
#     ${mysql} -e "FLUSH PRIVILEGES;"

#     DBSTATUS=1

# # If /root/.my.cnf doesn't exist then it'll ask for root password   
# else

#    read  -p 'Please enter root user MySQL password: ' rootpasswd
#    ${mysql} -u ${USER_NAME} -p${rootpasswd} -e "CREATE DATABASE ${MAINDB} /*\!40100 DEFAULT CHARACTER SET utf8 */;"
#    ${mysql} -u ${USER_NAME} -p${rootpasswd} -e "CREATE USER ${MAINDB}@localhost IDENTIFIED BY '${PASSWDDB}';"
#    ${mysql} -u ${USER_NAME} -p${rootpasswd} -e "GRANT ALL PRIVILEGES ON ${MAINDB}.* TO '${MAINDB}'@'localhost';"
#    ${mysql} -u ${USER_NAME} -p${rootpasswd} -e "FLUSH PRIVILEGES;"  
   
#    DBSTATUS=1
# fi

# echo ...

#   echo "Database was succesfully created with these detail: \n DB Name :${GR} ${MAINDB} ${NC} \n Username :${GR} ${MAINDB} ${NC} \n Password :${GR} ${PASSWDDB} ${NC} \n please save this for your references"
#   echo "Database and user creation : ${GR}DONE!${NC}"

# echo ''
# echo ...

# echo ${BL}"Importing dummy content to database (SQL Dump), please wait ..."${NC}

# #importing the sql dump database
# #sql databasenya filenya nanti akan dynamic based on paket dan cluster yang dipilih

# ${mysql} -u ${USER_NAME} -p${PASSWDDB} ${MAINDB} < ${PWD}/database.sql

# echo SQL Dump import : ${GR}DONE!${NC}
# echo 

#echo '... Deleting SQL Dump File'
#rm ngc_core_2022.sql


echo ${WH} "Step 7 -> Setting Environment" ${NC}

echo '... modifying ENV files for specific project credentials'

ENVFILE='.env'
if [ -f '.env' ]
then 
    echo "Environment file ${GR}found!${NC}, updating now... "
    #updating the .env file for domain name and database cred
    
    echo "working ..."
    sleep 1
    sed -i  "1s/.*/APP_NAME=${folder}/" "${ENVFILE}"
    sed -i  "4s/.*/APP_DEBUG=false/" "${ENVFILE}"
    sed -i  "5s~.*~APP_URL=http://${DOMAIN_NAME}/${folder}~" "${ENVFILE}"

    sed -i  "12s/.*/DB_DATABASE=${MAINDB}/" "${ENVFILE}"
    sed -i  "13s/.*/DB_USERNAME=${USER_NAME}/" "${ENVFILE}"
    sed -i  "14s/.*/DB_PASSWORD=${PASSWDDB}/" "${ENVFILE}"
    
   if [ $? -eq 0 ]; then
      echo "The .env file has been succesfully updated : ${GR}DONE!${NC}"
   else
    echo ${RED}"Failed to update file!"${RED}
   fi 
fi

echo 

#modifying myconfig.php 
echo '... modifying cms files for specific project name credentials'
cd public/ngc-cms/config
echo '... current directory =>' ${PWD}
echo 

#get myconfig file from myconfig.example.php
cp myconfig.example.php myconfig.php

echo '... updating cms myconfig file'
MYCONFIG='myconfig.php'
URLADMIN='http://'${DOMAIN_NAME}'/'${folder}'/';

if [ -f 'myconfig.php' ]
then 
    echo "myconfig file ${GR}found!${NC}, updating now... "
    #updating the myconfig file for domain name and database cred
    
    echo "working ..."
    sleep 1
    sed -i  "3s/.*/"'$SITE_NAME'"      ="'"'"${project_name}"'";'"/" "${MYCONFIG}"
    sed -i  "4s~.*~"'$SITE_URL'"       ="'"'${URLADMIN}'";'"~" "${MYCONFIG}"
   
   if [ $? -eq 0 ]; then
      echo "The myconfig.php file has been succesfully updated : ${GR}DONE!${NC}"
   else
    echo ${RED}"Failed to update file!, please update by yourself!"${RED}
   fi 
fi

echo 

#find connection.php
cp connection.example.php connection.php

echo '... updating cms connection file'
#update CMS connection file
CONNFILE='connection.php'

if [ -f ${CONNFILE} ]
then
    echo "Connection file ${GR}found!${NC}, updating now..."
    #updating the connection file
    echo "working ..."
    sleep 1
 
    sed -i  "7s/.*/"'$dbName'"="'"'${MAINDB}'";'"/" "${CONNFILE}"
    sed -i  "5s/.*/"'$dbUsername'"="'"'${USER_NAME}'";'"/" "${CONNFILE}"
    sed -i  "6s/.*/"'$dbPassword'"="'"'${PASSWDDB}'";'"/" "${CONNFILE}" 

    if [ $? -eq 0 ]; then
        echo "The connection file has been succesfully updated : ${GR}DONE!${NC}"
    else
        echo ${RED}"Failed to update file!"${RED}
    fi

else 
    echo "${RED}File not found${NC}"
fi    

echo ${GR} "Step 8, Done!" ${NC}

echo
sleep 1


echo 

#reminder
echo ${RED}${bold}'#### What can be done by a system should make your life easier.' ${NC} 
echo ${RED}${bold}'May the force always be with you 🖖🏻 ####' ${NC}

echo 
echo ${GR}${blink}"================ DONE =================="${NC}
echo ${GR}${blink}"NGC EARTH Installation Sequence Completed!"${NC}

duration=$SECONDS
echo "this installation process took $(($duration / 60)) minutes and $(($duration % 60)) seconds. v(^.^)v"

echo

echo ${BL}'NGC EARTH INSTALLER - V1.0 - (c) 2020, all right reserved!'${BL}
echo ${NC}


#end
