#!/bin/sh

set -x

if [ "$1" = "test" ]; then
    branch='test'
    location='/var/www/html-test'
    echo 'deploying to test.jjanzen.ca'
elif [ "$1" = "main" ]; then
    branch='main'
    location='/var/www/html'
    echo 'deploying to jjanzen.ca'
else
    echo 'unrecognized mode'
    exit 1
fi

rm -rf "$HOME/public_html"

cd ~/website || exit
git checkout "$branch"
git clean -f
git pull

cd ~/dotfiles || exit
git checkout main
git clean -f
git pull

cd ~/blog || exit
git checkout main
git clean -f
git pull

/bin/cp "$HOME/website/deploy.sh" /usr/local/bin

cd ~/dotfiles || exit
~/website/fix-dotfile-paths.sh
cd "$HOME" || exit
/usr/local/bin/emacs --batch -f package-initialize --script ~/website/publish.el
~/website/post-publish.sh

sed -i 's/) <a href=\"blog\//) <a href=\".\//' ~/public_html/blog/index.html
sed -i 's/<webMaster>.*<\/webMaster>/<webMaster>jjanzen@jjanzen.ca (jjanzen)<\/webMaster>/g' ~/public_html/rss.xml
sed -i 's/<author>.*<\/author>/<author>jjanzen@jjanzen.ca (jjanzen)<\/author>/g' ~/public_html/rss.xml

/bin/cp -r "$HOME/public_html"/* "$location"
chown -R apache:apache "$location"
chmod -R 775 "$location"
