#!/bin/bash
# Used in CI workflow: install and check for spelling errors
# Copyright © 2021 Aravinth Manivannan <realaravinth@batsense.net>
# 
# 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 <http://www.gnu.org/licenses/>.

readonly MISSPELL_DOWNLOAD="https://github.com/client9/misspell/releases/download/v0.3.4/misspell_0.3.4_linux_64bit.tar.gz"
readonly TMP_DIR=$(pwd)/tmp
readonly PROJECT_ROOT=$(pwd)
readonly MISSPELL_TARBALL="$TMP_DIR/misspell.tar.bz2"
readonly MISSPELL="$TMP_DIR/misspell"

set -Eeuo pipefail

source $(pwd)/scripts/lib.sh

FLAGS=""

help() {
	cat << EOF
spellcheck.sh: Check for spelling errors
USAGE:
    spellcheck.sh <options>
OPTIONS:
  c    --check   check for spelling erros
  h    --help    print this help menu
  w    --write   check and fix spelling errors
EOF
}



download() {
	if [ ! -e $MISSPELL ]; 
	then 
		echo "[*] Downloading misspell"
		wget --quiet  --output-doc=$MISSPELL_TARBALL $MISSPELL_DOWNLOAD;
		cd $TMP_DIR
		tar -xf $MISSPELL_TARBALL;
		cd $PROJECT_ROOT
		pip install codespell
	else
		echo "[*] Found misspell"
	fi
}

spell_check_codespell() {
	_check(){
		codespell $FLAGS $PROJECT_ROOT/$1 #|| true
	}
	_check README.md
	_check contents
}

spell_check_misspell() {
	mkdir $TMP_DIR || true
	download

	_check(){
		$MISSPELL $FLAGS $PROJECT_ROOT/$1
	}

	_check contents
	_check README.md
}

check_arg $1

if match_arg $1 'w' '--write'
then
	echo "[*] checking and correcting spellings"
	FLAGS="-w"
	spell_check_misspell
	spell_check_codespell
elif match_arg $1 'c' '--check'
then
	echo "[*] checking spellings"
	spell_check_misspell
	spell_check_codespell
elif match_arg $1 'h' '--help'
then
	help
else
	echo "undefined option"
	help
	exit 1
fi
