#!/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

#parameters
HOST=IP_MYSQL_HOST       #change
DB=bot_wa                #you can change  
USER=bot_wa              #you can change  
PASSWORD=bot_wa          #you can change  
DBADMIN_USER=admin       #change
DBADMIN_PASSWORD=passwd  #change
#end of parameters

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 "set old_passwords=0;grant all privileges on ${DB}.* to ${USER} identified by '${PASSWORD}';" |mysql -p${DBADMIN_PASSWORD} -u${DBADMIN_USER} -h${HOST}
echo "flush privileges;" |mysql -p${DBADMIN_PASSWORD} -u${DBADMIN_USER} -h${HOST}

echo "tables prepared"

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

echo "qrcode generate into folder ./qrcode"

sed -i 's/const cPath = ".\/"/const cPath = ".\/qrcode\/"/' index.js

#workaround no usable sandbox
sed -i "s/session: sessionData,/ 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

cd ..

docker stop bot_wa
docker rm bot_wa
docker rmi bot_wa

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

echo "Starting container"
docker run --name bot_wa --user bot_wa --rm -v `pwd`/qrcode:/home/bot_wa/app/qrcode -d bot_wa;sleep 2;docker logs bot_wa;sleep 2;docker logs bot_wa
