#!/bin/sh
#
# Copyright (c) 2007 Andrew Lewman

# TorPostflight gets invoked after any install or upgrade.

TARGET=$2/Library/Tor
TORDIR=$TARGET/var/lib/tor
LOGFILE=/var/log/tor.log
TORBUTTON_VERSION="1.2.1-fx"

# Check defaults for TARGET
if [ "$TARGET" == "//Library/Tor" ]; then
	TARGET=/Library/Tor
fi

# Create the tor directory, if it doesn't exist.
if [ ! -d $TORDIR ]; then
  mkdir -p $TORDIR
fi

# Check its permissions.
chmod 770 $TORDIR

# Check the logfile and make sure it exists.
if [ ! -f $LOGFILE ]; then
    touch $LOGFILE
    chown $TORUSER $LOGFILE
    chgrp daemon $LOGFILE
    chmod 660 $LOGFILE
fi

# Create the configuration file only if there wan't one already.
if [ ! -f $TARGET/torrc ]; then
  cp $TARGET/torrc.sample $TARGET/torrc
  chmod 660 $TARGET/torrc
fi

# Ensure symbolic links
cd /usr/bin
if [ -e /usr/bin/tor -a ! -L /usr/bin/tor ]; then
  mv tor tor_old
fi
if [ -e /usr/bin/tor-resolve -a ! -L /usr/bin/tor-resolve ]; then
  mv tor-resolve tor-resolve_old
fi
ln -sf $TARGET/tor .
ln -sf $TARGET/tor-resolve .

#cd /usr/share/man/man1
#MAN1=$TARGET/man/man1
#ln -sf $MAN1/*.1 .

if [ ! -e /var/log/tor -o -L /var/log/tor ]; then
  cd /var/log
  rm -f tor
fi

if [ -d /Library/StartupItems/Privoxy ]; then
  find /Library/StartupItems/Privoxy -print0 | xargs -0 chown root:wheel
fi

if [ -f $PACKAGE_PATH/Contents/Resources/uninstall_tor_bundle.sh ]; then
  cp $PACKAGE_PATH/Contents/Resources/uninstall_tor_bundle.sh $TARGET/uninstall_tor_bundle.sh
  chmod 550 $TARGET/uninstall_tor_bundle.sh
fi

# Copy Documentation
if [ -d $PACKAGE_PATH/Contents/Resources/documents ];then
   cp -r $PACKAGE_PATH/Contents/Resources/documents $TARGET/documents
fi

if [ -f /Applications/Firefox.app/Contents/MacOS/firefox ]; then
  if [ -f /Library/Torbutton/torbutton-$TORBUTTON_VERSION.xpi ]; then
      sudo -u $USER /Applications/Firefox.app/Contents/MacOS/firefox-bin /Library/Torbutton/torbutton-$TORBUTTON_VERSION.xpi
  fi
fi
