#!/bin/bash

#script asks for weather forecast and generates html file
#The html file is moved to the pi-display directory for disply"
#09DEC2022

my_dir="$(cd "$(dirname "$0")" && pwd)"
icons="![](file://${my_dir}/weather-icons/"
outfile=/run/user/$UID/weather.txt
html=/run/user/$UID/weather.html
pi_display=$HOME/pi-display/files/

#verify pandoc is installed
if ! hash pandoc 2>/dev/null; then
	echo "pandoc not found"
	echo "installing"
	sleep 2
	sudo apt-update
	sudo apt install -y pandoc
fi

#verify we have icons to work with
if [ ! -d $my_dir/weather-icons ]; then
	echo "Weather icons not found."
	exit 1
fi

HEADER(){
	clear;echo;echo
	echo " ############################"
	echo " # Weather Report Generator #"
	echo " ############################"
	echo 
}

IMAGE(){
	HEADER
	echo " (c)loudy, (p)artly-cloudy, (r)ain, (s)now, (cl)ear, (t)hunder-storms"
	read -p " $img weather image to use ? " image

	case $image in
		c)
			image=cloudy.jpg
		;;
		p)
			if [ "$img" = 'Tonight' ]; then
				image=cloudy-night.jpg
			else
				image=part-sun.jpg
			fi
		;;
		r)
			image=rain.jpg
		;;
		s)
			image=snow.jpg
		;;
		cl)
			if [ "$img" = 'Tonight' ]; then
				image=moon.jpg
			else
				image=sunny.jpg
			fi
		;;
		t)
			image=thunder.jpg
		;;
		sk)
			image=
		;;
		*)
			echo;HEADER;echo " not a valid choice. Please choose"
			echo " cloudy, part-sun, rain, snow, sunny or thunder"
			sleep 3
			IMAGE
		;;
	esac
}

#main menu
HEADER
read -p " What is the current temperture? " temp
#send user to image function to get weather image to use
img=Current
IMAGE
CUR_IMG=$image
read -p " Forcast for today? " day_forecast
#send user to image function to get weather image to use
img=Tonight
IMAGE
NIGHT_IMG=$image
read -p " Forcast for tonight? " night_forecast
#send user to image function to get weather image to use
img=Tomorrow
IMAGE
TOM_IMG=$image
read -p " Forcast for tomorrow? " tom_forecast

#output data to temp file
HEADER
echo "# Currently $temp" > $outfile
echo "${icons}${CUR_IMG})" >> $outfile
echo >> $outfile
echo "### $day_forecast" >> $outfile
echo "# Tonight" >> $outfile
echo "${icons}${NIGHT_IMG})" >> $outfile
echo >> $outfile
echo "### $night_forecast" >> $outfile
echo "# Tomorrow">> $outfile
echo "${icons}${TOM_IMG})" >> $outfile
echo >> $outfile
echo "### $tom_forecast" >> $outfile
echo >> $outfile
echo "### Last update `date`" >> $outfile

HEADER
echo "Generating HTML file"
cat $outfile | pandoc -s -o $html >/dev/null 2>&1
sed -i "s/title>-/title>Weather-`date`/" $html
rm $outfile
echo "moving html file to pi-display directory"
mv $html $pi_display

if ! grep weather.html $HOME/pi-display/links; then
	echo "weather.html,15" >> $HOME/pi-display/links
fi