#!/bin/sh

# This fs implements a simple database of your favourite ftp servers.
# The `archive' is a text file containing a list of ftp URL's one per line
# like this (followed optionaly by name under which the link will be
# shown - shouldn't contain spaces inside)
#
# ftp://sunsite.unc.edu/pub/Linux sunsite
# ftp://tsx-11.mit.edu/pub/linux tsx-11
# ftp://ftp.cvut.cz/pub/linux cvut
# ftp://jj@jfch.vc.cvut.cz:21/ my_machine
#
# You should refer only to directories, not to particular files.
# The file has to use `ftplist' extension (if you don't like it, change
# it in mc.ext resp. $HOME/.mc/ext). So the file name should match 
# regex ^.*ftplist$

# list fixed and copyout support by A'rpi/ESP-team

mcftplistfs_list ()
{
    { ls -l "$1"; cat "$1"; } | gawk -v uid=${UID-0} '
/^[\ \	]*(#.*)?$/ { next }
{
if (NF > 8) {
    a[1]=$6
    a[2]=$7
    a[3]=$8
    next
}
if ($1 ~ /^ftp:\/\//) {
    if ($1 ~ /\/$/) {
	a[4]=substr($1, 7, length($1) - 7)
	a[5]=$1
    } else {
        a[4]=substr($1, 7)
	a[5]=sprintf("%s/", $1)
    }
    if (NF >= 2)
	a[4]=$2
    else {
        i=split(a[4], b, "/")
        a[4]=b[1]
        for (j = 2; j <= i; j++)
            a[4]=sprintf("%s_%s", a[4], b[j])
    }
    printf "-rwxr-xr-x 1 %d %d %d %s %d %s %s\n", uid, 0, length(a[5]), a[1], a[2], a[3], a[4]
}
}' 2>/dev/null 
#> /tmp/hatred.txt 2>&1 #2>/dev/null
}

mcftplistfs_run ()
{
if [ -n "$MC_CONTROL_FILE" ]
then
    cat "$1" | gawk -v name=$2 '
/^[\ \	]*(#.*)?$/ { next }
{
if ($1 ~ /^ftp:\/\//) {
    if ($1 ~ /\/$/) {
	a[4]=substr($1, 7, length($1) - 7)
	a[5]=$1
    } else {
        a[4]=substr($1, 7)
	a[5]=sprintf("%s/", $1)
    }
    if (NF >= 2)
	a[4]=$2
    else {
        i=split(a[4], b, "/")
        a[4]=b[1]
        for (j = 2; j <= i; j++)
            a[4]=sprintf("%s_%s", a[4], b[j])
    }
    if (a[4] ~ name)
	printf "cd\n%s\n", a[5]
}
}' 2>/dev/null > $MC_CONTROL_FILE
fi
}

# Command: copyout archivename storedfilename extractto

mcftplistfs_copyout ()
{
if [ -n "$MC_CONTROL_FILE" ]
then
    cat "$1" | gawk -v name=$2 '
/^[\ \	]*(#.*)?$/ { next }
{
if ($1 ~ /^ftp:\/\//) {
    if ($1 ~ /\/$/) {
	a[4]=substr($1, 7, length($1) - 7)
	a[5]=$1
    } else {
        a[4]=substr($1, 7)
	a[5]=sprintf("%s/", $1)
    }
    if (NF >= 2)
	a[4]=$2
    else {
        i=split(a[4], b, "/")
        a[4]=b[1]
        for (j = 2; j <= i; j++)
            a[4]=sprintf("%s_%s", a[4], b[j])
    }
    if (a[4] ~ name)
	printf "%s\n", a[5]
}
}' 2>/dev/null > $3
fi
}


LC_ALL=C
export LC_ALL

case "$1" in
  list) mcftplistfs_list "$2"; exit 0;;
  run) mcftplistfs_run "$2" "$3"; exit 0;;
  copyout) mcftplistfs_copyout "$2" "$3" "$4"; exit 0;;
esac
exit 1
