#!/bin/sh

VERSION=8.5.5
DOWNLOAD_LANG=de
DOWNLOADS=/var/lib/linuxmuster-client-tor-browser-bundle/downloads/${DOWNLOAD_LANG}
CLEANUP=/var/lib/linuxmuster-client-tor-browser-bundle

mkdir -p $DOWNLOADS

# 32bit or 64bit
ARCH=`uname -m`

echo "Architecture with uname -m: $ARCH"
echo "Architecture manually set: $1"


# Manual override
case "$1" in
    "")
    # do nothing
    ;;
 
    32bit)
    ARCH=32bit
    ;;

    64bit)
    ARCH=64bit
    ;;

    cleanup)
    #ls -al  $CLEANUP
    echo "Removing $CLEANUP ...";
    rm -rf $CLEANUP
    exit
    ;;

    help)
    echo " "
    echo "Option: select architecture manually"
    echo "   32bit    : Download 32bit linux"
    echo "   32bit    : Download 64bit linux"
    echo "   cleanup  : Delete all downloads"
    echo " "

    exit
    ;;

    *)
    echo " "
    echo "Use option 'help' for information"
    echo " "
    exit 0
    ;;
esac



# Verifying
# Get the keys
# Erinn Clark
#gpg --keyserver x-hkp://pool.sks-keyservers.net --recv-keys 0x416F061063FEE659

OK=0

# Download
case "$ARCH" in
    i686|32bit)
    # 32bit Version
    FILE="tor-browser-linux32-${VERSION}_${DOWNLOAD_LANG}.tar.xz"
    WEB="https://www.torproject.org/dist/torbrowser/${VERSION}/"
    cd $DOWNLOADS; wget -t 10 -c --timestamping $WEB$FILE
    RES1=$?
    echo "Result download 1: $RES1"
    OK="$(($OK+$RES1))"
    cd $DOWNLOADS; wget -t 10 -c --timestamping $WEB$FILE.asc
    RES2=$?
    echo "Result download 2: $RES2"
    OK="$(($OK+$RES2))"
    #cd $DOWNLOADS; gpg --verify $FILE $FILE.asc
    ;;

    x86_64|64bit)
    # 64bit Version
    FILE="tor-browser-linux64-${VERSION}_${DOWNLOAD_LANG}.tar.xz"
    WEB="https://www.torproject.org/dist/torbrowser/${VERSION}/"
    cd $DOWNLOADS; wget -t 10 -c --timestamping $WEB$FILE
    RES1=$?
    echo "Result download 1: $RES1"
    OK="$(($OK+$RES1))"
    cd $DOWNLOADS; wget -t 10 -c --timestamping $WEB$FILE.asc
    RES2=$?
    echo "Result download 2: $RES2"
    OK="$(($OK+$RES2))"
    ;;

    *)
    echo " "
    echo "I dont know if you have 32bit or 64bit system"
    echo "Use option 'help' for information"
    echo " "
    exit 0
    ;;
esac


if [ $OK -eq 0 ]
then
    echo "All downloads were succesful: $OK";
    echo "Deleting all files not containing $VERSION ...";
    # remove all files NOT containing $VERSION string
    ls -1 $DOWNLOADS | grep -v "$VERSION" | xargs rm -vf
    echo "... done";

else
    echo "Not OK $OK";
fi


echo "########## DONE: Downloading tor browser bundles"
