#! /bin/bash

function veriffile() {
    if [[ $DIR == "/" ]]; then
        out="/$1"
    else
        out="$DIR/$1"
    fi
    DIR=$out
    if [[ $(adb shell "test -f $out; echo \$?" | tr -d '\r\n') -eq 0 ]] ; then
        adb pull "$out" "tmp/$(basename $out)"
        cat tmp/$(basename $out) |
        zenity \
            --text-info \
            --title='ZAndFile Editor' \
            --width='800' --height='600' \
            --editable \
            --filename=tmp/$(basename $out) > tmp/zandfile.out
        #rm -rf tmp/$(basename $out)
        if [[ $? -eq 0 ]]; then
            cat tmp/zandfile.out
            adb push "tmp/zandfile.out" "$out"
        fi
        listfile "$(dirname $DIR)" "$(adb shell ls -a $(dirname $DIR))"
    else
        listfile "$DIR" "$(adb shell ls -a $DIR)"
    fi
}

function listfile() {
    DIR=$1
    echo "$DIR"
    choice=$(zenity --list \
        --title="ZAndFile Listing" \
        --width="600" \
        --height="650" \
        --text="$1" \
        --separator="@" \
        --column="Liste des fichiers" \
            ".." \
            $(echo $2)
    )
    if [ "$?" -eq 1 ]; then
        rm -rf tmp
        exit
    fi

    case $choice in
        '..') nDIR=$(dirname $DIR); [ "$nDIR" == "/" ] && nDIR='/';  listfile "$nDIR" "$(adb shell ls -a $nDIR)";;
        *) ch=$(echo $choice | tr -d '\r\n') ; veriffile "$ch"
    esac
}
DIR=$1
mkdir tmp
adb shell mount -o remount,rw /
adb shell mount -o remount,rw /system
adb shell mount -o remount,rw /data
[ "$1" == "" ] && DIR='/'
listfile "$DIR" "$(adb shell ls -a $DIR)"
