#!/bin/bash

arch=$(uname -m)

pytis2gopath=$HOME/.local/share/pytis2go
pytis2gotgz=pytis2go-linux.tgz
appimagepath=$pytis2gopath/appimage
configpath=$HOME/.config/pytis2go
py2appimage=python2.7.18-cp27-cp27mu-manylinux1_$arch.AppImage
py3appimage=python3.7.13-cp37-cp37m-manylinux2014_$arch.AppImage

# Test existence of wget or curl

if which wget >/dev/null ; then
    cmd="wget -c  --no-check-certificate --user-agent=\"Mozilla\""
elif which curl >/dev/null ; then
    cmd="curl -O -k -#"
else
    echo "Cannot download, neither wget nor curl is available."
    exit 1
fi

url="https://ssl.is-it.eu/download"

download_image () {
    image_name=$1
    $cmd $url/$image_name.md5
    if [ ! -f $appimagepath/$image_name ] || ! md5sum -c $image_name.md5
    then
        echo "Downloading $image_name from $url/$image_name..."
        $cmd $url/$image_name
    fi
    if [ ! -f $appimagepath/$image_name ] || ! md5sum -c $image_name.md5
    then
        echo "Error downloading $image_name"
        return 1
    else
        return 0
    fi
}

if [ ! -d $pytis2gopath ]
then
    cd /tmp
    $cmd $url/$pytis2gotgz
    if [ ! -f /tmp/$pytis2gotgz ]
    then
        echo "Error downloading $pytis2gotgz"
        return 1
    fi
    tar xfz /tmp/$pytis2gotgz -C $HOME/.local/share
fi

[ ! -d $appimagepath ] && mkdir -p $appimagepath

cd $appimagepath

download_image $py3appimage || exit 1

download_image $py2appimage || exit 1

chmod +x $py3appimage

chmod +x $py2appimage

[ ! -L p2go-py3 ] && ln -sf $py3appimage p2go-py3

[ ! -L p2go-py2 ] && ln -sf $py2appimage p2go-py2

[ ! -L python3 ] && ln -sf $py3appimage python3

[ ! -L python2 ] && ln -sf $py2appimage python2

# Config broker

[ ! -d $configpath ] && mkdir -p $configpath

if [ ! -f $configpath/broker.conf ]
then
    echo "ssh://broker.is-it.eu" >$configpath/broker.conf
fi
