#!/bin/bash
## -*- coding: utf-8-unix -*-
## a wrapper to check required packages before running 

## Application name
APPLICATION=Minitube

## Path to executable binary
EXEC_BINARY="/usr/libexec/minitube"

## Packages(s): should install them when necessary packages are not found   
REQUIRED_PKGS="self-build-gstreamer-plugins-ffmpeg \
               self-build-gstreamer-plugins-bad"

## Packages(s): used to re-check after installation by synaptic
CONFIRM_PKGS="gstreamer-plugins-ffmpeg \
              gstreamer-plugins-bad"

INSTALL_TMPLIST=$(mktemp)

trap cleanup EXIT
cleanup() {
    rm -f $INSTALL_TMPLIST
}

case $LANG in
    ja*)  LOCALE=ja ;;
    *)    LOCALE=C ;;
esac

Msg_Text_C(){
    cat<<EOF
<big><b>Package installation required</b></big>

Your system does not have following package(s) necessary
to run $APPLICATION

 - `echo $INSTALL_PKGS | sed 's/ /\n - /g'`

Do you install above package(s)?
EOF
}

Msg_Text_ja(){
    cat<<EOF
<big><b>パッケージのインストールが必要です</b></big>

あなたのシステムには $APPLICATION の実行に必要な以下の
パッケージがインストールされていないようです

 - `echo $INSTALL_PKGS | sed 's/ /\n - /g'`

このパッケージをインストールしますか？
EOF
}

Msg_Failed_C(){
    cat<<EOF
build failed:

 - `echo $FAILED_PKGS | sed 's/ /\n - /g'`
EOF
}

Msg_Failed_ja(){
    cat<<EOF
ビルド失敗:

 - `echo $FAILED_PKGS | sed 's/ /\n - /g'`
EOF
}

## Check installed package(s)
for p in $REQUIRED_PKGS ; do
    if ! rpm -q $p > /dev/null 2>&1 ; then
        INSTALL_PKGS=$INSTALL_PKGS" "$p
    fi
done

## Ask installation
if [ -n "$INSTALL_PKGS" ]; then
    zenity --question \
        --title "$(basename $0)" \
        --text "$(Msg_Text_${LOCALE})"
    [ $? -eq 1 ] && exit 1

    ## 
    for p in $INSTALL_PKGS ; do
        echo $p" install\n" >> $INSTALL_TMPLIST
    done
    synaptic --non-interactive --hide-main-window --set-selections-file $INSTALL_TMPLIST

    ## Re-check package installation
    for p in $CONFIRM_PKGS ; do
        if ! rpm -q $p > /dev/null 2>&1 ; then
            FAILED_PKGS=$FAILED_PKGS" "$p
        fi
    done
    if [ -n "$FAILED_PKGS" ] ;then
        zenity --error \
                --title "$(basename $0)" \
                --text "$(Msg_Failed_${LOCALE})"
        exit 1
    fi
fi

$EXEC_BINARY $*
