#!/bin/bash
# starts whatsapp-web.js in docker, qrcode file is generated into qrcode, tables whatsapp_(out,in) are created in database on existing mysql host
# Prerequisites:
# running mysql database with rights to create db (on IP IP_MYSQL_HOST)
# docker on localhost

HOST=127.0.0.1               #change
DB=bot_wa                    #you can change
USER=bot_wa                  #you can change
PASSWORD=bot_wa              #you can change
DBADMIN_USER=admin           #change - must have all privileges with grant option
DBADMIN_PASSWORD=admin-pass  #change

rm -rf hbwhatsapi qrcode
git clone https://github.com/diegofazio/hbwhatsapi.git
mkdir qrcode
chmod 777 qrcode

cd hbwhatsapi

echo "------- preparing tables -------"
unzip db.zip
sed -i "s/harbourdb/${DB}/" db.sql

cat db.sql|mysql -p${DBADMIN_PASSWORD} -u${DBADMIN_USER} -h${HOST}
echo "------ Creating user ------"
echo "drop user '${USER}'@'localhost';" |mysql -p${DBADMIN_PASSWORD} -u${DBADMIN_USER} -h${HOST}
echo "create user '${USER}'@'localhost' identified with mysql_native_password by '${PASSWORD}';" |mysql -p${DBADMIN_PASSWORD} -u${DBADMIN_USER} -h${HOST}
echo "------ Granting all privileges ------"
echo "grant all privileges on ${DB}.* to '${USER}'@'localhost';" |mysql -p${DBADMIN_PASSWORD} -u${DBADMIN_USER} -h${HOST}
echo "------ Flushing privileges ------"
echo "flush privileges;" |mysql -p${DBADMIN_PASSWORD} -u${DBADMIN_USER} -h${HOST}

echo "------ tables prepared ------"

sed -i "s/harbourdb/${DB}/" index.js

echo "------ qrcode will be generate into folder ./qrcode -------"
sed -i 's/const cPath = ".\/"/const cPath = ".\/qrcode\/"/' index.js
sed -i "s/session: sessionData,/session: sessionData,\n   puppeteer: {\n      headless: true,\n      args: [\n         \"--no-sandbox\",\n         \"--disable-setuid-sandbox\",\n         \"--unhandled-rejections=strict\"\n      ]\n },/" index.js
sed -i "s/host: 'localhost'/host: '${HOST}'/" index.js
sed -i "s/user: 'harbour'/user: '${USER}'/" index.js
sed -i "s/password: ''/password: '${PASSWORD}'/" index.js
echo '------ for displaying qrcode ------'
sed -i "s/\/\/const qrcode = require('qrcode-terminal')/const qrcode = require('qrcode-terminal')"/ index.js
sed -i "s/qrcode_file.toFile(QR_CODE, qr);/qrcode_file.toFile(QR_CODE, qr);\nqrcode.generate(qr, {small: true});/"  index.js

cd ..

docker stop bot_wa
docker rm bot_wa

echo "------ Bulding docker image ------"
docker build . -t bot_wa

echo "------ Starting container ------"
docker run --name bot_wa --user bot_wa  --network="host"  -v `pwd`/qrcode:/home/bot_wa/app/qrcode -d bot_wa
#docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{{end}}'
docker logs bot_wa
sleep 20
#should display qrcode
docker logs bot_wa

