#!/bin/bash

set -e

DEST_DIR=~/gopher_compiled
FILE_NAME=upload.tar.gz
DEST_FILE=~/$FILE_NAME
HOST=tilde.pink
DEST_PATH=/~kati256/
USER=kati256

echo "Cleaning $DEST_DIR"
rm -rd $DEST_DIR/*
echo "Copying files"
cp -r * $DEST_DIR
echo "Deleting residual emacs files"
for FILE in `find $DEST_DIR -type f -name '*~'`
do
    rm $FILE
done
echo "Changing to host"
for FILE in `find $DEST_DIR -type f -iname 'index.gph'`
do
    sed -i "s/|localhost|/|$HOST|/g" $FILE
    sed -i "s+|/+|$DEST_PATH+g" $FILE
done
echo "Compilation complete"
cd $DEST_DIR
tar -czf $DEST_FILE *
echo "Upload file ready at $DEST_FILE"

echo "Deploying files"
scp $DEST_FILE $USER@$HOST:$FILE_NAME
ssh $USER@$HOST "gzip -c -d $FILE_NAME > tmp && tar -xf tmp -C public_gopher && rm tmp"
echo "Deploy complete"