#!/bin/ksh

# 'pharc' or 'phlog archiver' is a basic script to archive phlog posts
# on a yearly basis.
#
# Version: 2.0
#
# Depends on 'mkphlog', written by octotep. Otherwise it is completely useless
# unless you have your posts in the form $(date +%m-%d-%y). You are warned!!!
#
# Suggestions: -Use it with 'cron'. Ideally on December 31 just before midnight.
#                               55 23 31 12 *
#                               -To create a log: pharc 2>&1 >> pharc.log
#
# Copyright © 2012 Carlos Zuferri License GPLv3+: GNU
# GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
# This is free software: you are free to change and redistribute it.
# There is NO WARRANTY, to the extent permitted by law.
#
# TODO Improve it (As usual)
#

# Testing to see if the script can be run.

WORKDIR=$HOME/gopher/phlog

cd $HOME

if [ ! -d $WORKDIR ] ; then
       echo "$(date) No working directory found: $WORKDIR" ; exit 1
fi

if [ -d $WORKDIR/$(date +'%Y') ] ; then
       echo "$(date) Archive $(date +'%Y') already exists. Exiting..." ; exit 1
fi

if [ ! -d $WORKDIR/*-*-$(date +'%y') ] ; then
       echo "$(date) No phlog posts to archive." ; exit 1
else
       echo
       echo "$(date) Archiving phlog posts..."
fi

# Creating target directory and moving files there.

ARCHIVE=$(date +'%Y')

cd $WORKDIR
mkdir $ARCHIVE
chmod 750 $ARCHIVE
mv *-*-$(date +'%y') $ARCHIVE

# Creating && editing gophermaps.

cp gophermap $ARCHIVE/gophermaptemp
cd $WORKDIR/$ARCHIVE
sed /1Archive*/d < gophermaptemp > gophermap
chmod 640 gophermap
rm gophermaptemp

cd $WORKDIR

# Updating for mkphlog v.0.2

mv gophermap gophermaptemp
sed /1/d < gophermaptemp > gophermap
chmod 640 gophermap
rm gophermaptemp


DIRS=$(ls -d 20??)

for DIR in $DIRS
       do
               echo -e "1Archive $DIR\t$DIR" >> gophermap
       done
chmod 640 gophermap

sleep 2

echo
echo "$(date) You are done now."
echo

# "You can see the output of this script visiting my gopher hole at:"
# "<gopher://sdf.org/1/users/chals/>"

exit 0