#!/bin/bash

#########################################################################
# Bash script to make NEXC content disk                                 #
# Author: Abhishek Singh <abhishek.singh@olenepal.org>                  #
#########################################################################

set -e
set -u

#########################################################################
# Function defintions goes here                                         #
#########################################################################

# Function to check for a given file and its sha1 checksum exists
# Returns 0 if no file is provided as an argument
# Returns 1 if the file is provided, the sha1 checksum exists
# Returns 2 if the file is provided, but the sha1 checksum does not exist
# Returns 3 if the file does not exist
checkFileExists() {
	local result=0
	if [ $# -eq 0 ]
	then
		#echo "No file provided."
		result=0
	fi
	
	if [ -e $1 ]
	then
		if [ -e $1".sha1" ]
		then
			result=1
		else
			result=2
		fi
	else
		result=3
	fi
	echo "$result"
}

# Function to copy the give file with their sha1 checksum to the output dir
# Returns 0 if there are no arguments provided
# Returns 1 if both the file and its checksum is successfully copied
# Returns 2 if the file has been copied but it checksum failed to be copied
# Returns 3 if the checksum has been copied but the file failed to be copied
# Returns 4 if both the file and the checksum failed to be copied
copyFile() {
	local result=0
	if [ $# -eq 0 ]
	then
		#echo "No file provided."
		return 0
	fi
	cpyFile=0
	cpyChecksum=0
	fileToCopy=$1
	outDir=$outputDir
	# Try to copy the file to output directory
	cp $fileToCopy $outDir
	
	if [ $? -eq 0 ]
	then
		cpyFile=1
	fi

	# Try to copy the sha1 sum to output directory
	cp $fileToCopy".sha1" $outDir
	
	if [ $? -eq 0 ]
	then
		cpyChecksum=1
	fi

	# Check for the status codes and return an appropriate value
	if [[ $cpyFile -eq 1 && $cpyChecksum -eq 1 ]]
	then
		result=1
	fi
	if [[ $cpyFile -eq 1  && $cpyChecksum -eq 0 ]]
	then
		result=2
	fi
	if [[ $cpyFile -eq 0 && $cpyChecksum -eq 1 ]]
	then
		result=3
	fi
	if [[ $cpyFile -eq 0 && $cpyChecksum -eq 0 ]]
	then
		result=4
	fi
	echo "$result"
}

# Function to display the status message depending upon the output of the copyFile function
showStatus() {
	if [ $# -eq 0 ]
	then
		echo "No arguments provided."
		return 0
	fi
	case $1 in
		1)
			echo "The file and its checksum has been successfully copied."
			;;
		2)
			echo "The file was copied successfully but its checksum failed to be copied."
			;;
		3)
			echo "The checksum was copied successfully but the file failed to be copied."
			;;
		4)
			echo "Both the file and the checksum failed to be copied."
			;;
	esac
}

# Define the current working directory from where the script starts
curDir=$(pwd)

# Define the directory where the samba share would be mounted
mountDir=/tmp/nexc

# Check if the user has root privileges
if [ $EUID -ne 0 ]
then
	echo "You need the root privileges to run this script."
	exit 1
fi

# Check if already mounted. If yes, unmount before use
isMounted=$(mount | grep -i $mountDir | wc -l )
if [ $isMounted -gt 0 ]
then
	umount $mountDir
	if [ ! $? -eq 0 ]
	then
		echo "NEXC directory already mounted. Unmount failed. Please make sure it is not in use."
		exit 1
	fi
fi

# Check if the mountDir is available
if [ -d "$mountDir" ]
then
    rm -Rf $mountDir
    mkdir -p $mountDir
else
    mkdir -p $mountDir
fi

if [ $# -eq 0 ]
then
	echo "You need to provide the path to the output directory as an argument to the script."
	exit 1
else
	outputDir=$1
fi

# Try mounting the samba share to the mountDir
echo "Trying to mount the source."
mount //192.168.5.20/Deployment $mountDir -o ro,username=olenepal,password=olenepal

# Check if the mount operation was successful
if [ $? -ne 0 ]
then
	echo "The mount operation failed with an error code $?."
	exit 1
fi

# Enter the mount directory
cd $mountDir"/NEXC/"

# Get a list of all the directories
dirlist=$(ls -l | grep '^d' | awk '{print $9}')

# Display user a list of directories to choose from
echo "Please make a selection from the following list:"
iCount=1
for dir in $dirlist
do
	echo $iCount") "$dir
	(( iCount +=1 ))
done
echo -n "Enter your choice (1,2,3,...): "
read choice

# Enter the selected directory
iCount=1
selmade=0
ver=0
for dir in $dirlist
do
	if [ $iCount -eq $choice ]
	then
		cd $dir"/"
                ver="$dir"
		selmade=1
		break	
	fi
	(( iCount +=1 ))
done

if [ $selmade -eq 0 ]
then
	echo "You are required to make a selection. Please rerun the script."
	exit 1
fi

# Make content defintions
fedoradata=nexc-fedora.tar.bz2
fedoradb=nexc-fedora.sql
fezcode=nexc-fez.tar.bz2
fezdb=nexc-fez.sql
sabdakoscode=nexc-sabdakos.tar.bz2
sabdakosdata=nexc-sabdakos.sql
wiki4schools=nexc-wiki4schools.tar.gz
wiktionaryinterwiki=nexc-wiktionary-interwiki.sql
wiktionarypagearticle=nexc-wiktionary-pages-articles.sql.gz
externalcontent=nexc-ext-content.tar.bz2
extdata=nexc-ext-data.sql

# Try to extract fedora-data to outputDir
cd fedora-data
feddata=$(checkFileExists $fedoradata)
if [ $feddata -eq 1 ]
then
	echo "Extracting Fedora datastream (nexc-fedora.tar.bz2) to $outputDir.It will take a while, please wait."
	tar -xjf nexc-fedora.tar.bz2 -C $outputDir
	if [ $? -eq 0 ]
	then
		echo "Extraction successful."
	else	
		echo "Extraction failed with exit code $?."
	fi
fi

# Try to copy fedora db dump
feddb=$(checkFileExists $fedoradb)
if [ $feddb -eq 1 ]
then
	echo "Copying Fedora database dump (nexc-fedora.sql) to $outputDir."
	fedDBCopy=$(copyFile $fedoradb)
	showStatus $fedDBCopy
fi
cd ..

# Try to copy fez codebase
cd fez-code
fezCodeBase=$(checkFileExists $fezcode)
if [ $fezCodeBase -eq 1 ]
then
	echo "Copying Fez codebase (nexc-fez.tar.bz2) to $outputDir."
	fezCodeCopy=$(copyFile $fezcode)
	showStatus $fezCodeCopy
fi
cd ..

# Try to copy fez db dump
cd fez-data
fezDBDump=$(checkFileExists $fezdb)
if [ $fezDBDump -eq 1 ]
then
	echo "Copying Fez database dump (nexc-fez.sql) to $outputDir."
	fezDBCopy=$(copyFile $fezdb)
	showStatus $fezDBCopy
fi
cd ..

# Try to copy sabdakos codebase
cd sabdakos-code
sabdakosCodeBase=$(checkFileExists $sabdakoscode)
if [ $sabdakosCodeBase -eq 1 ]
then
	echo "Copying Sabdakos codebase (nexc-codebase.tar.bz) to $outputDir."
	sabdakosCodeCopy=$(copyFile $sabdakoscode)
	showStatus $sabdakosCodeCopy
fi
cd ..

# Try to copy sabdakos db dump
cd sabdakos-data
sabdakosDB=$(checkFileExists $sabdakosdata)
if [ $sabdakosDB -eq 1 ]
then
	echo "Copying Sabdakos database dump (nexc-sabdakos.sql) to $outputDir."
	sabdakosDBCopy=$(copyFile $sabdakosdata)
	showStatus $sabdakosDBCopy
fi
cd ..

# Try to copy wiki4schools
cd wiki4schools
wiki4schoolsCodeBase=$(checkFileExists $wiki4schools)
if [ $wiki4schoolsCodeBase -eq 1 ]
then
	echo "Copying wiki4schools (nexc-wiki4schools.tar.gz) to $outputDir."
	wiki4schoolsCopy=$(copyFile $wiki4schools)
	showStatus $wiki4schoolsCopy
fi
cd ..

# Try to copy wiktionary interwiki
cd wiktionary
wikint=$(checkFileExists $wiktionaryinterwiki)
if [ $wikint -eq 1 ]
then
	echo "Trying to copy wiktionary interwiki (nexc-wiktionary-interwiki.sql) to $outputDir."
	wikintCopy=$(copyFile $wiktionaryinterwiki)
	showStatus $wikintCopy
fi

# Try to copy wiktionary page article
wikpgart=$(checkFileExists $wiktionarypagearticle)
if [ $wikpgart -eq 1 ]
then
	echo "Trying to copy wiktionary pages articles (nexc-wiktionary-pages-articles.sql.gz) to $outputDir."
	wikpgartCopy=$(copyFile $wiktionarypagearticle)
	showStatus $wikpgartCopy
fi
cd ..

# Try to extract external content to outputDir
cd external-content
ext=$(checkFileExists $externalcontent)
if [ $ext -eq 1 ]
then
	echo "Extracting external content for fez (nexc-ext-content.tar.bz2) to $outputDir."
	tar -xjf nexc-ext-content.tar.bz2 -C $outputDir
	if [ $? -eq 0 ]
	then
		echo "Extraction successfull."
	else
		echo "Extraction failed with exit code $?."
	fi
fi
cd ..

# Try to copy Video data
cd ext-data
vdta=$(checkFileExists $extdata)
if [ $vdta -eq 1 ]
then
	echo "Trying to to copy Extra database dump (nexc-ext-data.sql) to $outputDir."
	vCpy=$(copyFile $extdata)
	showStatus $vCpy
fi
cd ..

# Set up xo activities
echo "Copying xo activities."
cd $mountDir"/NEXO/activities/"
mkdir $outputDir/xs-activity-server/
cp *.xo $outputDir/xs-activity-server/
cd $outputDir/xs-activity-server/
sha1sum *.xo > manifest.sha1

# Move to outputDir
cd $outputDir

# Clone the NEXC-maint repo from hg.olenepal.org for fedora and wikitionary install
echo "Setting up install environment."
hg -q clone http://hg.olenepal.org/NEXC-maint
cd NEXC-maint/
mv nexc-fedora-install ../
mv nexc-wiktionary-install ../
cd ..
rm -Rf NEXC-maint/

# Set up fedora-install
echo "Setting up fedora install environment."
cd nexc-fedora-install
wget -q http://dev.olenepal.org/Uploads/fedora-2.2.1-installer.jar
wget -q http://dev.olenepal.org/Uploads/fedora-2.2.1-installer.jar.md5
cd ..
echo "Setting complete."

# Set up wiktionary-install
echo "Setting up wiktionary install environment."
cd nexc-wiktionary-install
wget -q http://dev.olenepal.org/Uploads/mediawiki-1.15.1.tar.gz
md5sum mediawiki-1.15.1.tar.gz > mediawiki-1.15.1.tar.gz.md5
cd ..
echo "Setting complete."

# write the version for NEXC on the disk
cd $outputDir
touch NEXC.version
echo $ver > NEXC.version

# change to the starting directory
cd $curDir

#Change file permissions
echo "Setting file permissions."
chmod -R 755 $outputDir

#unmounting the source
echo "Unmounting the source."
umount $mountDir

if [ $? -ne 0 ]
then
    echo "Unable to unmount source. Quitting."
    exit 5
else
    rm -Rf $mountDir
fi

#try to unmount the destination
strLen=${#outputDir}
lastChar=${outputDir:strLen-1}
if [ $lastChar == "/" ]
then
    outputDirNew=${outputDir:0:strLen-1}
else
    outputDirNew=$outputDir
fi
isMounted=$(mount | grep $outputDirNew | wc -l)
if [ $isMounted -eq 1 ]
then
    sleep 5
    echo "Unmounting destination."
    umount $outputDir
fi

echo "Creation of NEXC disk/folder complete."
exit 0
