#!/bin/bash
#
#   pkg-magic - controlling script for kde-servicemenus-pkg-tools
#
#   Copyright (c) 2013-2014 artoo <flower_of_life@gmx.net>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.

shopt -s nullglob

VERSION=0.9

popup(){
    kdialog --title "Pkg-tools" --passivepopup "$1"  10
}

run(){
    konsole --noclose --hide-menubar --workdir "${rundir}" -e "${cmd}"
}

get_link(){
    local html='<a href="'"$1"'">'"$1"'</a>'
    echo ${html}
}

truncate(){
    local temp=${1##*/}
    local ret=${temp%%-[0-9]*}
    echo $ret
}

get_db_name(){
    local name=${rundir##*/} ext="tar.xz"
    case ${name} in
        'x86_64'|'i686'|'any')
            rd=$(dirname ${rundir})
            rn=${rd##*/}
            rdb="${rn}.db.${ext}"
        ;;
        *) rdb="${name}.db.${ext}" ;;
    esac
    echo ${rdb}
}

add_pkgs(){
    cmd="repo-add ${rundir}/$(get_db_name) ${OPTS}"
}

rm_pkgs(){
    local list=()
    for u in ${OPTS[@]};do
        list+=($(truncate $u))
    done
    cmd="repo-remove ${rundir}/$(get_db_name) ${list[@]}"
}

get_graph(){
    local pn=$(truncate ${uri}) fn ext="png"
    fn="${graphdir}/${pn}.${ext}"
    echo "$(pactree ${OPTS} ${pn})" | dot -T ${ext} > "${fn}"
    popup "$(get_link "${fn}")"
}

graphdir=${XDG_PICTURES_DIR:-~/pactree_graphs}

if ! [[ -d ${graphdir} ]];then
    mkdir -p ${graphdir}
fi

is_makepkg=false
is_repo_add=false
is_repo_remove=false
is_namcap=false
is_pactree=false
is_config=false
is_checksum=false

rundir=$(pwd)
cmd=''

actions='t:c:n:m:af:rf'

while getopts "${actions}" arg;do
    case ${arg} in
        m) is_makepkg=true; uri="${OPTARG}" ;;
        c) is_checksum=true; cmd="updpkgsums" ;;
        a) is_repo_add=true ;;
        r) is_repo_remove=true ;;
        n) is_namcap=true; uri="${OPTARG}" ;;
        t) is_pactree=true; uri="${OPTARG}" ;;
    esac
done

OPTS=("${*:$OPTIND}")

if ${is_makepkg}; then
    cmd="makepkg ${OPTS}"
    run
elif ${is_checksum};then

    run
elif ${is_namcap}; then
    cmd="namcap ${OPTS} ${uri}"
    run
elif ${is_repo_add};then
    add_pkgs
    run
elif ${is_repo_remove};then
    rm_pkgs
    run
elif ${is_pactree};then
    get_graph
fi
