# File: iotubu   ---  script by tsaiwn@cs.nctu.edu.tw
# ## Script to deploy IoTTalk Server automatically
#  #########################   for Ubuntu version, by tsaiwn
iotuser='iotsvr'
# Default account name is iotsvr, you can modify the above LINE
# Python or uwsgi, Default --  NOT use uwsgi
useUWSGI='no'      
##############################################################2019/01/22
rcfile='/etc/rc.local'
# ## if for CentOS/Fedora :   rcfile='/etc/rc.d/rc.local'
sudodir=/etc/sudoers.d
pyver="Python-3.6.5"
iotDir='./iottalk_server_1.0'
# ######
CAN_SUDO=$(sudo -n uptime 2>&1|grep "load"|wc -l)
if [ ${CAN_SUDO} -le 0 ]; then
  cat <<===BADNEWS

 !  ?   sudo access privilege problem  無法用 sudo     ?  !
 !  Note:  注意 ..
 !   You must run this script with sudo access privilege  !
 !   你必須有 sudo 權限才有辦法成功執行這個 Script        !
 !                                                        !
 !  Please use another account to run this script.        !
 !  You can login as root to do so.                       !
 !  請用 root  或其他有 sudo 權限的帳號執行這腳本         !
 !  !  Please  check using  ls -al /etc/sudoers.d      !  !
 !         Bye !  Leaving this script now ..   Bye Bye !  !

===BADNEWS
   return
fi
###
sudo apt update
sudo apt install wget -y

###
echo   #blank line
cat << ===ENDNOTE
# ##################################################
# This script will do:
# (1) Add user $iotuser account  IF necessary (when it does NOT exist)
#     You may change value of the variable iotuser
# (2) Make the user $iotuser as an SUdoer (Let him can use sudo with NO password)
# (3) Grab source code for iotTalk Server from GitLAB ( Authorization required!!)
##    Please give your gitLAB account name to Dr. Yun-Wei Lina
##    Send mail to him, 林芸蔚博士); His Email is  jyneda@gmail.com     
# (4) Install Mail utility    ---  move to here for interactive answer
# (5) Install/Update necessary system Software / Utility
# (6) Install Python 3.6.5
# (7) Install  iottalk_server_1.0
# (8) append command line to /etc/rc.local to  make iotTalk server Run automatically
# (9) Need manually do 'sudo visudo' to modify secure_path
# ### Aften source this script, Reboot your machine, if using CentOS
# #########################################
#
# ! ! ! ! ! !  NOTE   --  need your gitLAB account and password to git clone ...
# Now use git clone to grab the IoTTalk server source code required authorization
===ENDNOTE
echo
echo "Now iottalk server source code requires authorization"
echo "To get authorization:   Please:"
echo "   Send your gitLAB account 帳號  to Dr. Lin  林芸蔚博士; His E-Mail is  jyneda@gmail.com"
# Answer y  or  yes  to confirm that you have been authorized to git clone our source code
ans=0
while [ $ans -le 0 ]; do
  read -p "Do you have gitLAB account and has been authorized: " yesno
  echo
  case "$yesno" in
    y|Y|yes|Yes|YES ) ans=1;;
    n|N|no|No|NO ) ans=38;;
    * ) ans=0;;
  esac
done
if [ $ans -eq 38 ]; then
  echo
  echo "Get a gitLAB account 請申請一個 gitLAB 帳號, 然後 then .."
  echo " Send your gitLAB account 帳號  to Dr. Lin  林芸蔚博士; His E-Mail is  jyneda@gmail.com"
  echo Bye !
  echo
  return
fi

#
# need username for gitLAB
lenuser=3
while [ $lenuser -le 3 ]; do
  echo
  read -p " Give me your GITLAB username at gitLAB.com: " gituser
  lenuser=${#gituser}
  if [ ${lenuser} -lt 4 ]; then
     echo "!!! gitLAB username: $gituser NOT accepted!!!\n Should be more than 3 chars !!!"
  fi
done
echo  "PASSWORD required for the gitLAB account!"

lenpass=3
while [ $lenpass -le 3 ]; do
  echo
  read -p " Give me your password for $gituser in gitLAB.com: " gitpass
  lenpass=${#gitpass}
  if [ ${lenpass} -lt 4 ]; then
     echo enter your passwd for gitLAB account
  fi
done
echo  # blank line
# gitLAB account passwd OK
# echo $gituser $gitpass



#origdir="$PWD"
alias os='cat /etc/os* | head -6'
osname=`cat /etc/os-release | head -1`
echo "# OS (Operating System)  $osname"

### check OSNAME, this script is for Ubuntu

if [[ $osname != *"Ubu"* ]]; then
  cat <<===OSDIFF
  ## This Script is for Ubuntu system 
  ##  這腳本是給  Ubuntu 作業系統用的 !
  ## Should you DO this on purpose, please reply  y or yes
  ##  如果你確定故意要繼續, 請回答 y
  ##
===OSDIFF
  echo " !!! System OS may NOT be compatible with this script !!!"
  echo "     If you do this on purpose, answer y"
  read -p "Are you sure(n, y)? "  # -n 1 -r
  echo    # move to a new line
  # default (Enter ONLY) is no
  if  ! [[ $REPLY =~ ^(yes|y|Y|YES|Yes)$ ]]; then
    echo 'iotubu   is for Ubuntu OS'
    echo 'iotcen   is for CentOS OS'
    echo 'iotfed   is for Fedora OS'
    echo '============================================='
    echo 'Bye !'
    echo
    return
  fi
  echo "OK  I will go ahead  ..."
fi
#########################################################################################

cat <<===UWSGI
################### Run web via using UWSGI + Nginx ?   ####################
###
### ..Do you want to run Iottalk server via using  UWSGI + Nginx  ???
###
###   Run iottalk via uwsgi with Nginx should have BETTER Performance !
###   Answer y  or  yes   if you want to run uwsgi + Nginx
###
===UWSGI
###

yesno=''
while [ "$yesno" = "" ]; do
   read -p "Do you want to use UWSGI + Nginx? " yesno
done
useUWSGI="$yesno"
echo "useUWSGI === $useUWSGI"
  if [[ "$yesno" =~ ^(y|Y|yes|YES|Yes)$ ]]; then
     useUWSGI='yes'
     echo
     echo "We will use Nginx + uwsgi for iottalk web server"
     echo
  fi
##############################


# ##
echo '# ============================================================= #'
echo "# Default IoTTalk Server account user is $iotuser"
echo "#  IoTTalk Server 會用帳號  $iotuser  且此帳號會有 sudo 權限    #"
echo "# If you want to change it to other user, modify the var iotuser at line 4"
echo IoTtalk Account in this Server will be $iotuser
###
echo   #blank line
cat << ===ENDNOTE2
# ##################################################
# This script will do:
# (1) Add user $iotuser account  IF necessary (when it does NOT exist)
#     You may change value of the variable iotuser
# (2) Make the user $iotuser as an SUdoer (Let him can use sudo with NO password)
# (3) Grab source code for iotTalk Server from GitLAB ( Authorization required!!)
##    Please give your gitLAB account name to Dr. Yun-Wei Lina
##    Send mail to him, 林芸蔚博士); His Email is  jyneda@gmail.com     
# (4) Install Mail utility    ---  move to here for interactive answer
# (5) Install/Update necessary system Software / Utility
# (6) Install Python 3.6.5
# (7) Install  iottalk_server_1.0
# (8) append command line to /etc/rc.local to  make iotTalk server Run automatically
# (9) Need manually do 'sudo visudo' to modify secure_path
# ### Aften source this script, Reboot your machine
# #########################################
#
===ENDNOTE2

tmpdir=/tmp
origdir="$PWD"
echo ====== Current Directory is $PWD

echo "the iotTalk Server will run using the account  $iotuser"
echo "If you want to use other account, answer no to this question"
echo "the iotTalk 系統將安裝在這帳號:  $iotuser"
echo "如果要換別的帳號請結束這腳本, 並手動修改第四列的 iotuser 變數值"
read -p "Want to use account (用帳號)  $iotuser  繼續嗎 continue(n, y)? "  # -n 1 -r
echo    # move to a new line
if  ! [[ $REPLY =~ ^(yes|y|Y|YES|Yes)$ ]]; then
   echo '------------------------------------------------------------------------'
   echo " 請手動修改這 iotubu 檔案的第四列的 iotuser 變數值後, 重新 source iotubu"
   echo '========================================================================'
   echo 'Bye !'
   return
fi
echo "If account $iotuser not exist, 如帳號不存在, 會自動建立, 並設定為 sudoer "
echo ##

sleep 2

#  #########################   for Ubuntu version
#  #
# ### if for CentOS/Fedora :   rcfile='/etc/rc.d/rc.local'
# # Default IoTTalk user is iotsvr
# # If you want to change it to other user, modify the variable iotuser at line 4
echo IoTtalk Account will be $iotuser

#  #########################
#  ###################################
echo
echo '#  #######################################################'
echo "# (1) About to Add user  $iotuser  account IF NECESSARY"
# ##
echo
echo "Remind you again:"
echo '=== The user name for iotTalk Server  would be ' $iotuser
echo '=   You can change it in the very beging line'
echo

haveuser=`grep $iotuser /etc/passwd | wc -l`
if [ $haveuser -le 0 ]; then
   echo "  !!! "
   echo "  !!!!!!! account NOT exist 帳號 $iotuser 不存在 !!!!!!"
   echo "  Will create account names $iotuser"
   echo "  將會建立帳號   $iotuser"
   echo "  Will create account names $iotuser since it is NOT exist."
   echo 

 myname=`whoami`
 echo 'The current working directory is' "$PWD"
 echo "current user is $myname"
 echo "About to create the account  $iotuser ..."
 echo
# #read -p " Give the Password (at lease 8 char) for $iotuser: " passvar
passvar="nopass"
plen=${#passvar}
while [ $plen -lt 8 ]
do
 read -p " Give the  Password ( at least 8 characters ) for $iotuser: " passvar
 plen=${#passvar}
 if [ $plen -ge 8 ]; then
  break;
 fi
 if [ $plen -eq 0 ]; then
  break;
 fi
 echo "Too short"'!'" Please input at least 8 characters"'!'
done
###
if [ "GG$passvar" == "GG" ]; then
  # there is no password input by you .. so ..
  echo
  passvar=acm"$iotuser".123
  echo "You do NOT give the password for $iotuser, "
  echo using default password $passvar
  echo '!!!!!!!!!!'
fi
#######
### addUserTmpFile=`mktemp auser.XXXtmp`
### echo $iotuser >  $addUserTmpFile
### echo $passvar >> $addUserTmpFile
### sudo adduser $iotuser < $addUserTmpFile
#######

# ##############################################
# # Note: do NOT modify the following 13 Lines
addUserTmpFile=`mktemp addUser.XXXtmp`
cat > $addUserTmpFile << ======
$passvar
$passvar
iotTalk user
MIC311
Work Phone
HomePhone
for Run IoTTalk Server
y

======
# Do NOT modify the above 11 Lines

sudo adduser $iotuser < $addUserTmpFile

# delete the temporary file  $addUserTmpFile
/bin/rm -f $addUserTmpFile
###
# ###############################################
# # for CentOs
if [[ $osname == *"Cen"* ]]; then
  sudo passwd $iotuser << ======
$passvar
$passvar
======
  # # sudo userdel user_you_want_to_delete
  sudo chmod 755 /home/$iotuser
fi
# # for Fedora
if [[ $osname == *"Fed"* ]]; then
  sudo passwd $iotuser << =====
$passvar
$passvar
=====
  # # sudo userdel user_you_want_to_delete
  sudo chmod 755 /home/$iotuser
fi
###
# ###############################################
if [[ $osname != *"Ubuntu"* ]]; then
   echo "======  OS is Not Ubuntu  *********************************"
   echo 'Hint:   to delete a user please use userdel instead of deluser'
   alias deluser='userdel'
fi
#
echo
echo "Add user $iotuser OK    ; you can check /etc/passwd"
echo
echo ====== ====== ====== ====== ====== ====== ======
echo '# ###############################################'
cat /etc/passwd | grep $iotuser
echo ====== ====== ====== ====== ====== ====== ====== ======
echo ###
sleep 3
# ######################################################

else
   echo 
   echo "Already have account $iotuser  !!!"
   echo "已經有帳號  $iotuser  !!!"
   echo "已經有帳號  $iotuser  !!!"
   echo "已經有帳號  $iotuser  !!!"
   echo "Already have account $iotuser  !!!"
   echo 
fi


# ######################################################
# (2) Make the user $iotuser as an SUdoer (Let him can use sudo with NO password)
echo "# (2) Make the user $iotuser as an SUdoer ; Let him can use sudo with NO password"
## Make user $iotuser as an SUDOer, so that it CAN RUN sudo without PASSWORD
sudo touch $sudodir/$iotuser
yyy="$iotuser ALL=(ALL) NOPASSWD : ALL"
sudo su root -c "echo '$yyy' >> $sudodir/$iotuser"
sudo chmod 0440  $sudodir/$iotuser
echo '################################################'
echo "### ### ### files in $sudodir ### ### ###"
 echo "# the Sudoers ... in $sudodir ============"
sudo ls -al $sudodir
#echo "###### Note the the user $iotuser is now an SUdoer ##############################"
echo
sleep 3
#



#####(3)  Grab the iottalk_server_1.0   using git clone
echo
echo "About to Grab iottalk server source code from gitLAB (authorization required)"
# move git clone to here (3)  Grab the iottalk_server_1.0   using git clone
echo "# (3)  Grab the iottalk_server_1.0   using git clone"
#make sure we have git, wget, vim

sudo apt-get install wget -y

sudo apt install git -y
sudo apt-get install git -y

sudo apt install vim -y
sudo apt-get install vim -y

### cd "~$iotuser"
cd /home/$iotuser
## iotDir='./iottalk_server_1.0'
backupDir="$iotDir.$(/bin/date +%m%d)_$(/bin/date +%0k%0M%0S).$(($RANDOM%10))"
if [ -d "$iotDir" ]; then
   echo "## Found an OLD $iotDir"
   echo "##  . . . Will be renamed to $backupDir"
   sleep 3
   sudo mv $iotDir $backupDir
fi
#
# Grab the iotTalk Server from Git Hub
# sudo su $iotuser -c 'git clone https://IoTtalk_Share:iottalkshare2016@bitbucket.org/IoTtalk/iottalk_server_1.0.git'
# # Now require Authorization; You need a GitLab account, and ..
# # Please contact "林勻蔚"<jyneda@gmail.com>
###
 cat <<===NEEDAUTH
# Grab the iotTalk Server from GitLAB
### Now require Authorization; You need a GitLab account, and ..  ###
### Please contact "林勻蔚"<jyneda@gmail.com>                     ###
===NEEDAUTH
#

# Grab the iotTalk Server from GitLAB

cd /home/$iotuser
echo
echo "the user name is $iotuser"
echo "current Directory is /home/$iotuser"
echo "about to do git clone ..."
echo
sudo su $iotuser -c "git clone https://$gituser:$gitpass@gitlab.com/IoTtalk/iottalk-v1.git iottalk_server_1.0"
echo '-------- ======== -------- -------- ===============  ########################'
if [[ $osname != *"Ubuntu"* ]]; then
 sudo chmod 755 $iotDir
fi


### Make sure we have startup_wsgi.sh which is for using uwsgi with Nginx
cd /home/$iotuser
cd $iotDir
cd setup

rndtmpfile="startup.OLD.$(/bin/date +%m%d)_$(/bin/date +%0k%0M%0S).$(($RANDOM%10))$(($RANDOM%10))"
if [ -e startup.sh ]; then
   #sudo su $iotuser -c " cp -p startup.sh $rndtmpfile"
   sudo cp -p startup.sh $rndtmpfile
   echo "=== Note that your  OLD startup.sh  has been renamed to $rndtmpfile"
fi
##

## Obtain startup_wsgi.sh form iottalk.vip if it does NOT exists
if ! [ -e startup_wsgi.sh ]; then
  sudo su $iotuser -c 'wget iottalk.vip/startup_wsgi.sh -N'
  sudo su $iotuser -c 'chmod +x startup_wsgi.sh'
fi

# if want to use UWSGI, copy startup_wsgi.sh onto  startup.sh 


# ######################################################
echo "# (5) Install/Update necessary system Software / Utility"
#
cd /home/$iotuser
# Disable Auto Indent (noai) in vi/vim
sudo su $iotuser -c "echo ':setl noai nocin nosi inde=' >> /home/$iotuser/.vimrc"
# sudo su $iotuser -c "echo ':set number' >> /home/$iotuser/.vimrc"
###  :set nonumber     if you do NOT want to show Line Number in vi/vim

## rename .screenrc if it exists
## rndfile=".screenrc.OLD.$(($RANDOM%10))$(($RANDOM%10))"
## rndfile=".screenrc.OLD.`/bin/date +%m%d`.$(($RANDOM%10))$(($RANDOM%10))"
rndfile=".screenrc.OLD.$(/bin/date +%m%d)_$(/bin/date +%0k%0M%0S).$(($RANDOM%10))$(($RANDOM%10))"
if [ -e .screenrc ]; then
   sudo mv .screenrc $rndfile
   echo "=== Note that your OLD .screenrc has been renamed to $rndfile"
fi
##
echo "# (5a..) get .screenrc from iottalk.vip/screenrc"
echo '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
echo  === === Now the user is `whoami`
pwd
echo 'The current working directory is' "$PWD"
echo --------------------------------------------------------
echo --------------------------------------------------------
rndfile="screenrc.OLD.$(/bin/date +%m%d)_$(/bin/date +%0k%0M%0S).$(($RANDOM%100))"
if [ -e screenrc ]; then
   sudo mv screenrc $rndfile
   echo "=== Note that your OLD screenrc has been renamed to  $rndfile"
fi
##
sudo su $iotuser -c 'wget iottalk.vip/screenrc -N'
sudo su $iotuser -c 'cp -p screenrc .screenrc'
# ##
sudo apt-get update -y
sudo apt-get upgrade -y
sudo apt-get install screen -y
###
echo "# (5b..) sqlite3, it's devel, openssl and it's devel"
 # sudo apt-get install sqlite -y
 sudo apt-get install sqlite3 libsqlite3-dev -y
 sudo apt-get install openssl  -y
 sudo apt-get install libssl-dev -y

  
# ##
echo "# (5c..)  install build-essential: gcc/g++, ..."
# gcc/g++ ...
# # # sudo apt-get install build-essential
 # for CentOS:
 #sudo yum groupinstall "Development Tools"  -y
echo ====== will cost a while ...
sudo apt-get install build-essential -y
#
echo "# (5d..)  zip related"
#zlib
sudo apt-get install ruby -y
sudo apt-get install zlib1g -y
sudo apt-get install zlib1g-dev -y

# ######################################################
# ## Prepare/Install Python3
echo "# (6) Install Python 3.6.5  ================="
echo '----------- !!!!!!!!!! !!!!!!!!!!! -----------'
echo "# (6a..) obtain Python source , then unzip it ..."
pwd
sudo su $iotuser -c 'wget https://www.python.org/ftp/python/3.6.5/Python-3.6.5.tgz -N'
sudo su $iotuser -c 'tar xzvf Python-3.6.5.tgz'
# ##  Build Python3
echo "# (6b..) Configure Python with prefix /usr/local ..."
##
if [[ $osname != *"Ubuntu"* ]]; then
 sudo chmod 755 "$pyver"
fi
 cd $pyver
# require 2 minutes
echo configure Python parameters
echo wait around 2 minutes ...
#
sudo su $iotuser  -c './configure --prefix=/usr/local'
 echo "# (6c..) generate Makefile using make -j 2 ..."
sudo su $iotuser  -c 'make -j 2  '
 echo "# (6d..) Install Python3 into system directory /usr/local/* ..."
sudo su $iotuser -c 'sudo -H make install'
#
 echo "# (6e..) Upgrade pip3 utility ..."
sudo su $iotuser -c 'sudo -H pip3 install --upgrade pip'


# #########################################################
echo "# (7) Install  iottalk_server_1.0"
 echo "# move git clone to (3)  Grab the iottalk_server_1.0   using git clone"



echo "# (7A..)  DO:  sudo -H pip3 install -r requirements.txt"
cd /home/$iotuser
cd $iotDir

passfile='password.txt'
### fix password.txt NOT Found cause by csmapi.py  #2018/08/31
if ! [[ -e "$passfile" ]]; then
   sudo su  $iotuser -c "echo 'passWORDWHY' >> $passfile"
fi
#####

pwd
 sudo -H su $iotuser -c 'sudo -H pip3 install -r requirements.txt'
 #sudo -H su $iotuser -c 'sudo -H pip3 install Werkzeug==0.14.1'

################## 2018/12/20
echo "# (7c..)  DO:  Install uwsgi along with  libpcre3 libpcre3-dev "
## we have changed to   run iottalk server using uwsgi
### install uwsgi
sudo -H apt install libpcre3 libpcre3-dev -y
sudo -H pip3 install uwsgi

# Note now need nginx to do reverse proxy for uwsgi web application

## iotDir='./iottalk_server_1.0'
cd /home/$iotuser
cd $iotDir/lib
echo "# (7d..)  DO:  Modify lib/wsgi_csm.ini, lib/ccm/wsgi_ccm.ini"
# need to modify lib/wsgi_csm.ini
#modify the lib/wsgi_csm.ini  (change username from iottalk to $iotuser)
echo "modify the lib/wsgi_csm.ini  (change username from iottalk to $iotuser) .."
sudo sed -i "s/iottalk/$iotuser/" wsgi_csm.ini

echo
echo '=== file lib/wsgi_csm.ini'
cat  wsgi_csm.ini
echo ===CSM====================================================
echo

# need to modify lib/ccm/wsgi_ccm.ini
#modify the lib/ccm/wsgi_ccm.ini  (change username from iottalk to $iotuser)
echo "modify the lib/ccm/wsgi_ccm.ini  (change username from iottalk to $iotuser) .."
cd /home/$iotuser
cd $iotDir/lib/ccm
sudo sed -i "s/iottalk/$iotuser/" wsgi_ccm.ini

echo
echo '=== file lib/ccm.wsgi_ccm.ini'
cat  wsgi_ccm.ini
echo ===ccm====================================================
echo

###    if want uwsgi + Nginx   ====================================
###    if want uwsgi + Nginx   ====================================
###    if want uwsgi + Nginx   ====================================

if [[ "$useUWSGI" == "yes" ]]; then
 cd /home/$iotuser
 cd $iotDir
 cd setup
 #cp -p startup_wsgi.sh startup.sh
 #sudo su $iotuser -c 'cp  startup_wsgi.sh startup.sh'
 sudo -H su $iotuser -c 'cp -p startup_wsgi.sh startup.sh'
 ######
 ################   Nginx      #####################
 ### Nginx
 ###
 echo
 echo "# (7e..)  DO:  sudo -H apt-get install nginx -y"
 ################  Nginx - Install nginx  
 ################  nginx   -- then check/modify /etc/nginx/sites-available/*
 ################  nginx    --- then, check links in /etc/nginx/sites-enabled/
sudo -H apt-get install nginx -y

#need to modify the default configuration file
#we can use another file other than default to config Nginx
#and then, of course, reload the nginx server
#sudo vim /etc/nginx/sites-available/default
#sudo nginx -s reload

echo "# (7f..)  DO:  obtain nginx config file wsgi_nginx_conf"
################   config file for Nginx: wsgi_nginx_conf      #####################
# obtain the config file from iottalk.vip
cd /home/$iotuser
sudo su $iotuser -c 'wget iottalk.vip/wsgi_nginx_conf -N'

echo "# (7g..)  DO:  modify wsgi_nginx_conf and copy to  /etc/nginx/sites-available/"
 ### check/modify wsgi_nginx_conf 
sudo sed -i "s/iottalkuser/$iotuser/g" wsgi_nginx_conf

### then copy it onto  /etc/nginx/sites-available/
#copy this file to  /etc/nginx/sites-available/
##sudo cp -p wsgi_nginx_conf /etc/nginx/sites-available/
sudo -H su -c 'cp  wsgi_nginx_conf /etc/nginx/sites-available/'


### .. then enable via ls links in /etc/nginx/sites-enabled/
#
#disable the nginx default
echo
echo "sudo rm /etc/nginx/sites-enabled/default"
echo
sudo rm /etc/nginx/sites-enabled/default
ls -l  /etc/nginx/sites-enabled/
##
#always put those config files in /etc/nginx/sites-available/
#make the wsgi_nginx_conf  enabled
### .. then enable via ls links in /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/sites-available/wsgi_nginx_conf /etc/nginx/sites-enabled/

#if you want to enable the default:
# sudo ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/
# to check if enabled:
# ls -l  /etc/nginx/sites-enabled/
#

# to test rules in /etc/nginx/sites-enabled/
# sudo nginx -t


# to restart nginx (reload rules)
# sudo nginx -s reload
# sudo systemctl restart nginx

# force  nginx to stop 
sudo systemctl stop nginx
#start it again
sudo systemctl start nginx



cat <<==MEMONGINX

#######  Commands to control nginx  ###############
# sudo systemctl status nginx 

# sudo systemctl start nginx 
# sudo systemctl stop nginx 
# sudo systemctl restart nginx

# sudo systemctl disable nginx
# sudo systemctl enable nginx

#   sudo nginx -s reload

#############################################

==MEMONGINX



###### ###### ######## https
###### ###### ######## https --  install  python-certbot-nginx from ppa:certbot/certbot
###### ###### ######## https

cat <<===CERTBOT
###
# To enable https://   (port 443), .. 
#
# You have to do the following steps to using Let's Encrypt CA

sudo apt-get update
sudo -H apt-get install software-properties-common -y
sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo -H apt-get install python-certbot-nginx -y
sudo certbot --nginx
sudo nginx -s reload
=============================================================

===CERTBOT

fi

###########  ENDIF  for using uwsgi + Nginx
###########  ENDIF  for using uwsgi + Nginx
###########  ENDIF  for using uwsgi + Nginx  #####  if [ useUWSGI ==  "yes" ]; then
###########  ENDIF  for using uwsgi + Nginx  #####  if [ useUWSGI ==  "yes" ]; then
###########  ENDIF  for using uwsgi + Nginx
###########  ENDIF  for using uwsgi + Nginx

if  [[ "$useUWSGI" == "yes" ]]; then
   sudo systemctl enable nginx
fi
if ! [[ "$useUWSGI" == "yes" ]]; then
   sudo systemctl stop nginx
   sudo systemctl disable nginx
fi



# ##
#
# ##########################################################################
echo "# (8) append command line to /etc/rc.local to  make iotTalk server Run automatically"
#
# cd /etc/rc.d    #Centos / Fedora
echo -------------------------------------------------
echo '=== === If CentOs/Fedora :  cd /etc/rc.d'
if ! [[ -e "$rcfile" ]]; then
 yyy="'#!/bin/sh -e'"
 sudo su root -c "echo $yyy >> $rcfile"
fi
### sudo su root -c 'echo "# haha" >> /etc/rc.local'
ggg="sudo -u $iotuser /home/$iotuser/iottalk_server_1.0/setup/startup.sh"
echo The var ggg is $ggg
echo ===============================================================================
sudo su root -c "echo $ggg >> $rcfile"
# ## another way to do so: 
# ## pwd
# ## cd $tmpdir
# ## pwd
# ## tmpfile=`mktemp add2RCLocal.XXXtmp`
# ## echo $ggg >> $tmpfile
# ## sudo su root -c "cat $tmpfile >> $rcfile"
# #######
##
NOW=`date`
sudo su root -c "echo '# at $NOW' >> $rcfile"
sudo su root -c "echo '###### ======' >> $rcfile"
##
# ######
# # fix for Ubuntu 16.x, because it's /etc/rc.local has "exit 0"
#  check /etc/rc.local to see if there is "exit 0"
HAS_EXIT0=$(sudo cat $rcfile | grep "^exit 0" | wc -l)
if [ ${HAS_EXIT0} -gt 0 ]; then
   echo '== comment out OLD " exit 0 " '
   sudo sed -i "s/^exit 0/#exit 0/" $rcfile
   #and then append "exit 0" again
   sudo su root -c "echo 'exit 0' >> $rcfile"
fi
#
echo "====== ====== ###### === $rcfile should be OK now=== ###### ====== ======"
#
######
echo "Note that the file $rcfile SHOULD HAVE +x permission"
sudo chmod +x $rcfile
echo === === If CentOs/Fedora :  cat /etc/rc.d/rc.local
ls -al  $rcfile
cat $rcfile
echo === === === ^^^^^^^^^^^^^^^ === === ===
###### recover access mode of  /home/$iotuser
if [[ $osname == *"Fedo"* ]]; then
  sudo chmod 700 /home/$iotuser
fi
if [[ $osname == *"Cent"* ]]; then
  sudo chmod 700 /home/$iotuser
fi
###
#  
echo '# ###############################################################################'
echo "# (7)                            ====================== "
echo "# (7) mail utility:  mail/mailx"
 ## sudo apt-get install mailutils -y
 ## disable all interactive actions
sudo DEBIAN_FRONTEND=noninteractive apt-get -yq install mailutils

echo
echo 'If you found the command "ifconfig" is missing on your Ubuntu .. '
echo '  the function of ifconfig command can be done by the command ip'
echo '  use the command "ip" instead of ifconfig'
echo 'or if you insist, install it using "sudo apt install net-tools"'
echo '===------------------^^^^^^^^^^^^^^^^^^^^^^^^^^==='
echo

echo "# (9) Need manually do 'sudo visudo' to modify secure_path if using CentOS"
echo
# ### Aften source this script, Reboot your machine, if using CentOS

############
osname=`cat /etc/os-release | head -1`
if [[ $osname == *"Cent"* ]]; then
 cat << ===END===
      # ## ############################################################ # ##
        #======  OS is Not Ubuntu  *************************************#
         ## #                                                       # ##
       #     (8) Do the following manually :                             #
  #  Add  /usr/local/bin to secure_path   using  sudo visudo                  #
 #     a) sudo visudo                                                            #
#      b) find secure_path  using  /secur   and then modify that LINE                 #
#      c) Make sure /usr/local/bin in the  secure_path,  like the following line:     #
 #   Defaults    secure_path = /usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin        #
 #   ------------------------- ^^^^^^^^^^^^^^^-----------------------------        #
  # ##                                                                         # ##
      # ##          /usr/local/bin    MUST be in secure_path                 # ##
       # ##                                                                 # ##
        # ##          You are using CentOs !                               # ##
           # ## ==================================================== # ##
===END===
fi

######
echo "= = = = = Current working Directory is $PWD"
#
cd $origdir
echo ============= Now in $origdir =============
echo "###  ###  Current user is `whoami`"
echo "= = = = = Current working Directory is $PWD"
thisfilename="${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}"
echo "######## done of  $thisfilename"
echo "######## ^^^^^^^^^^^^^^^^^^^^^^ ########"
#sudo service ssh status
#sudo service ssh restart
#this is the LAST LINE of this file

