#!/bin/bash - 
#===============================================================================
#
#          FILE: lib_utils.sh
# 
#         USAGE: ./lib_utils.sh 
# 
#   DESCRIPTION: functions for scripts used to update local HPR installations 
#				 using the HPR static site generator
# 
#       OPTIONS: ---
#  REQUIREMENTS: mysql2sqlite (https://github.com/dumblob/mysql2sqlite)
#          BUGS: ---
#         NOTES: ---
#        AUTHOR: Roan "Rho`n" Horning <roan.horning@gmail.com>
#       CREATED: 02/26/2023 03:27:08 PM -5 UTC
#      REVISION: ---
#       LICENSE: GNU AGPLv3 
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <https://www.gnu.org/licenses/>.	
#
#===============================================================================

set -o nounset                              # Treat unset variables as an error

#---  FUNCTION  ----------------------------------------------------------------
#          NAME:  make_working_dir
#   DESCRIPTION:  Creates a local temporary working directory
#				  SEE: https://stackoverflow.com/questions/4632028/how-to-create-a-temporary-directory#answer-34676160
#    PARAMETERS:  
#       RETURNS: The path to the working directory 
#-------------------------------------------------------------------------------
function make_working_dir { 

	# the directory of the script
	local DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

	# the temp directory used, within $DIR
	# omit the -p parameter to create a temporal directory in 
	# the default location
	
	local WORK_DIR=`mktemp -d -p "$DIR"`

	# check if tmp dir was created
	if [[ ! "$WORK_DIR" || ! -d "$WORK_DIR" ]]; then
		echo "Could not create temp dir"
		exit 1
	fi
	echo $WORK_DIR
}

#---  FUNCTION  ----------------------------------------------------------------
#          NAME:  clean_working_dir
#   DESCRIPTION:  Remove local temporary working directory 
#    PARAMETERS: WORK_DIR -- Temporay directory to be delted
#       RETURNS:  
#-------------------------------------------------------------------------------
function clean_working_dir {

	if [[ -d $1  ]] && expr $1 : '.*/tmp.*' ; then
		rm -rf $1
		echo "Deleted temp working directory $1" 
	else
		echo "Did not delete directory: $1"
		echo "Not a temporary directory."
	fi
	
}

#---  FUNCTION  ----------------------------------------------------------------
#          NAME:  download_hpr_sql
#   DESCRIPTION:  Download the HPR SQL dump file into a working directory 
#    PARAMETERS:  
#       RETURNS:  
#-------------------------------------------------------------------------------
function download_hpr_sql { 

	if [[ ! -d $1  ]] || ! expr $1 : '.*/tmp.*' ; 
	then
		echo "Please provide the temporary directory when calling this function"
		return 1
	fi

	local CURL=`which curl`
	local WGET=`which wget`
	local HPR_URL=https://www.hackerpublicradio.org/hpr.sql

	if [ -f $1/hpr.sql ];
	then
		echo "Removing temporary hpr.sql"
		rm $1/hpr.sql
	else
		echo "No temporary hpr.sql to remove"
	fi

	if [ "$CURL" != "" ]; 
	then
		curl $HPR_URL --output $1/hpr.sql
		echo "Downloaded hpr.sql via curl"
	elif [ "$WGET" != "" ];
	then
		wget --directory-prefix=$1 $HPR_URL
		echo "Downloaded hpr.sql via wget"
	else
		echo "Could not download file. Please install either curl or wget."
		return 1
	fi
}

#---  FUNCTION  ----------------------------------------------------------------
#          NAME:  make_hpr_sqlite_db
#   DESCRIPTION:  Converts the hpr sql file into an sqlite db file
#    PARAMETERS:  
#       RETURNS:  
#-------------------------------------------------------------------------------
function make_hpr_sqlite_db { 

	if [[ ! -d $1  ]] || ! expr $1 : '.*/tmp.*' ; 
	then
		echo "Please provide the temporary directory when calling this function"
		return 1
	fi

	local MYSQL2SQLITE=`which mysql2sqlite`
	local BIN_PATH=""

	if [ "$MYSQL2SQLITE" = "" ];
	then
		if [ $# -gt 1 ] && [ -z "$2" ];
		then
			BIN_PATH=$2
		else
			BIN_PATH=`find . -type f -name "mysql2sqlite" -print | head -1`
			if [ "$BIN_PATH" != "" ]; 
			then
				BIN_PATH=${BIN_PATH/mysql2sqlite//}
			else
				echo "Could not find mysql2sqlite script."
				return 1
			fi
		fi
	fi
	echo $BIN_PATH

	if [ -f $1/hpr.db ];
	then
		rm $1/hpr.db
	fi

	# Remove lines from hpr.sql that mysql2sqlite can't handle
	sed '/^DELIMITER ;;/,/^DELIMITER ;/d' < $1/hpr.sql > $1/hpr-sqlite.sql

	${BIN_PATH}mysql2sqlite $1/hpr-sqlite.sql | sqlite3 $1/hpr.db
	echo "Created hpr.db"
}

#---  FUNCTION  ----------------------------------------------------------------
#          NAME:  copy_to_public_dir
#   DESCRIPTION: Move HPR sql and db files to public website folder 
#    PARAMETERS:  
#       RETURNS:  
#-------------------------------------------------------------------------------
function copy_to_public_dir { 

	if [ $# -gt 1 ] && [ ! -z "$1" ] && [ ! -z "$2" ];
	then
		cp $1/hpr.sql $2/hpr.sql
		cp $1/hpr.db $2/hpr.db
		return 0
	else 
		echo "Bad arguments. Can't copy files to public directory."
	fi
}
