#!/bin/sh

NAME=lostvikings
VERSION=1.0

POST_MESSAGE="/var/adm/update-messages/lostvikings-1.0-10.27-1"

SERVER="http://emu-land.net/consoles/snes/roms?act=getfile&id=816"
FILE="lostvikings.7z"

CURL_OPTIONS="-L -s --speed-limit 3500 --speed-time 15"

if ( ! which id > /dev/null ) || ( ! which tar > /dev/null ); then
    echo "Running in non-chrooted (install into directory) mode... Exit safely."
    exit 0
fi

if [ "$(id -u)" != 0 ]; then
    echo "error: You must be root to use this application!"
    exit 1
fi

. "/etc/sysconfig/proxy"

if [ "$PROXY_ENABLED" != no ]; then
    if [ -n "$HTTP_PROXY" ]; then
        export http_proxy="$HTTP_PROXY"
    fi
fi

if [ -z $http_proxy ]; then
    echo
    echo "note: No proxy is used. Please set the environment variable \"http_proxy\""
    echo "note: to your favourite proxy if you want to use a proxy for the download."
    echo "note:"
    echo "note:   sh: export http_proxy=\"http://proxy.example.org:3128/\""
    echo "note:   csh: setenv http_proxy \"http://proxy.example.org:3128/\""
fi

tmpdir="$(mktemp -d "/tmp/$(basename $0).XXXXXX")"
trap "rm -rf $tmpdir" EXIT
if [ $? -ne 0 ]; then
    echo "$0: Can't create temp dir, exiting..."
    exit 4
fi

cd "$tmpdir"

success=false
for server in $useserver $SERVER; do
    archive="$server"
    rm -f "$FILE"
    echo "$FILE ($archive):"
    echo -n "  Fetching   ... "
    curl $CURL_OPTIONS -o "$FILE" "$archive"
    if [ $? -ne 0 ]; then
        rm -f "$FILE"
        echo "failed ... deleted!"
        continue
    fi
    success=true
    echo "done"
    break
done

if [ "$success" != false ]; then 
    # Extract.
    7z e "$FILE"
    rm -f "$FILE"
    # Install.
    install -Dm 0644 "Lost Vikings, The (G).smc" "/usr/share/lostvikings/lostv-de.smc"
    install -Dm 0644 "Lost Vikings, The (S).smc" "/usr/share/lostvikings/lostv-es.smc"
    install -Dm 0644 "Lost Vikings, The (E) [!].smc" "/usr/share/lostvikings/lostv-en_GB.smc"
    install -Dm 0644 "Lost Vikings, The (U) [!].smc" "/usr/share/lostvikings/lostv-en_US.smc"
    install -Dm 0644 "Viking no Daimeiwaku (J).smc" "/usr/share/lostvikings/lostv-ja.smc"
    rm -f "/usr/share/lostvikings/lostv.smc"
    ln -s "lostv-en_GB.smc" "/usr/share/lostvikings/lostv.smc"

    echo "*** Lost Vikings files installed. ***" | tee $POST_MESSAGE
else
    echo "*** No Lost Vikings files installed. ***" | tee $POST_MESSAGE
fi
