#!/bin/bash

d=`date +%Y%m%d`

prj_root=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )
cd "$prj_root"

log2file() {
	echo "sh: $1" >> "$prj_root/log/$d.log"
}

error_exit() {     
	log2file "Error: $1"     
	exit 1 
}

touch "$prj_root/log/$d.log"
echo "log: $d" >> "$prj_root/log/$d.log"

log2file "Starting update.sh"
fromdate=$(ls -1 *_latest.mcl |grep -Eo '[[:digit:]]{8}') || error_exit "cannot latest mcl file"

echo $fromdate

python3 update_missing.py >> "$prj_root/log/$d.log"

log2file "Moving old file to archive"
mv "$prj_root/$fromdate""_latest.mcl" "$prj_root/archive/""$fromdate"".mcl" || error_exit "cannot mv to archive"


log2file "git add"
git add "*_latest.mcl" "Deleted_Comics.txt" "archive/*" "log/*" >> "log/$d.log" || error_exit "cannot git add"

#log2file "git rm"
#git rm "$fromdate""_latest.mcl" >> "log/$d.log" || error_exit "cannot git rm"

log2file "git commit"
git commit -m "Updated $d" >> "log/$d.log" || error_exit "cannot git commit"

log2file "git push"
git push origin master >> "log/$d.log" || error_exit "cannot git push"