#!/bin/bash
#Fatih USTA <fatihusta@labrisnetworks.com>

set -e 
set -x

prefix=/opt
debian_dir=$(pwd)/debian
tmp_dir=${debian_dir}/ahtapot-mhn-tmp
mhn_home=${prefix}/mhn

clean_old_files () {
    supervisorctl stop all
    rm -rf ${prefix}/{nginx.conf.template,GeoIPASNum.dat,GeoLiteCity.dat,GeoLiteCityv6.dat,honeymap,hpfeeds,mhn,mnemosyne,www}
    rm -f /etc/nginx/sites-available/default
    rm -f /etc/supervisor/conf.d/*.conf

    mongo hpfeeds --eval "db.dropDatabase();"
    mongo mnemosyne --eval "db.dropDatabase();"
}

#clean old data
rm -rf ${tmp_dir}
clean_old_files 

#Create Directories
mkdir -p ${tmp_dir}/{var/log,opt/mongo_initial_db,/etc/supervisor} ${mhn_home}

#MHN Directory
chmod +x ${debian_dir}/../scripts/install_mongodb_pardus17.sh

#Copy Source to $prefix
cp -a ${debian_dir}/../* ${mhn_home}/

#Remove Debian Files
rm -rf ${mhn_home}/debian

#Generate Config File
cd ${mhn_home}/server && \
python generateconfig.py unattended --email mhn@ahtapot.org --password ahtapot --base_url http://169.254.2.254 --honeymap_url http://169.254.2.254:3000 --mail_server localhost --mail_port 25 --mail_user user@ahtapot.org --mail_pass ahtapot --mail_sender noreply@ahtapot.org --log_file_path /var/log/mhn/mhn.log

#Run install
cd ${mhn_home} && ./install.sh --no-elk-splunk

#Copy Files to Debian Directory
cp -a ${prefix}/{GeoIPASNum.dat,GeoLiteCity.dat,GeoLiteCityv6.dat,honeymap,hpfeeds,mhn,mnemosyne,www} ${tmp_dir}/opt/
cp -a /etc/supervisor/conf.d/ ${tmp_dir}/etc/supervisor/
cp /etc/nginx/sites-available/default ${tmp_dir}/opt/nginx.conf.template
cp -a /var/log/mhn/ ${tmp_dir}/var/log/

#Dump Mongo Database
mongodump --out ${tmp_dir}/opt/mongo_initial_db/

#Clean Again
clean_old_files 

#Return Build Dir
cd ${debian_dir}/../
