#!/bin/ksh

# 'pharc' or 'phlog archiver' is a basic script to archive phlog posts
# on a yearly basis.
#
# 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
#
# 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

cd $WORKDIR

# Creating target directory and moving files there.

ARCHIVE=$(date +'%Y')

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

# Creating && editing gophermaps.
# I use: sed -e '1d' -e /1Archive*/d < gophermaptemp > gophermap
# Adapt to your needs.

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

# I also use: echo -e "0About\tabout" > gophermap
# Adapt to your needs.

cd $WORKDIR

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