#!/usr/bin/env bash
#
# Set the values of the following variables to match your environment
# TODO: Make these options use a config file
#
# phlog root path
PHLOG_PATH="$HOME/gopher/phlog"
# template for new post directory names (default`date +%F`, ie. 2017-10-10)
POST_TEMPLATE=$(date +%F)

if [ ! -d "${PHLOG_PATH}" ]; then
	 echo "Can't find ${PHLOG_PATH}. Aboriting..."
	 exit 1
fi

usage() {
	 cat <<EOF
Usage: $0 [build|publish]
	build:
		Builds the skeleton of a new post

	publish:
		Publishes the requestsed post
EOF

}

build() {
	 post_dir="${PHLOG_PATH}/${POST_TEMPLATE}"
	 # I'm currently only posting once per day so this is fine
	 if [ -d "${post_dir}" ]; then
		  echo "${post_dir} already exists. Aborting..."
		  exit 1
	 fi
	 mkdir "${post_dir}"
	 chmod 0755 "${post_dir}"
	 touch "${post_dir}/gophermap"    # Empty placeholder for phlog post
	 chmod 0644 "${post_dir}/gophermap"
}

publish() {
	 # Shuffle files around and generate new gophermap
	 date=$(date +%F)
	 rm "${PHLOG_PATH}"/gophermap.last  # delete old gophermap backup
	 mv "${PHLOG_PATH}"/gophermap "${PHLOG_PATH}"/gophermap.last  # backup gophermap
	 rm "${PHLOG_PATH}"/post.list.last  # delete old post.list
	 mv "${PHLOG_PATH}"/post.list "${PHLOG_PATH}"/post.list.last  # backup post.list
	 # make new post
	 cat <<EOF > "${PHLOG_PATH}"/post.new
1(${date}) ${title}	/users/${USER}/phlog/${POST_TEMPLATE}	sdf.org	70
EOF
	 # write header to new gophermap
	 cat "${PHLOG_PATH}"/header >> "${PHLOG_PATH}"/gophermap
    # concat new post with old posts
	 cat "${PHLOG_PATH}"/post.new "${PHLOG_PATH}"/post.list.last >> "${PHLOG_PATH}"/post.list
	 # write posts to gophermap
	 cat "${PHLOG_PATH}"/post.list >> "${PHLOG_PATH}"/gophermap
	 # adjust permissions
	 chmod 0644 "${PHLOG_PATH}"/gophermap
	 chmod 0600 "${PHLOG_PATH}"/gophermap.last
	 # cleanup
	 rm "${PHLOG_PATH}"/post.new

# Bump phlog listing in index
	 phlog
	 sleep 2
	 phlog
}

case $1 in
	build)
		build
		;;
	publish)
		shift
		title=$@    # take anything after "publish" and make post title
		publish
		;;
	*)
		usage
		;;
esac
