#! /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$
#
# If you add "#define WANT_PARSE" to main.c you will be able to hit return
# on the filenames in order to connect to the ftp servers.
#

mcftplistfs_list ()
{
    { ls -l $1; cat $1; } | @AWK@ -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 "lrwxrwxrwx   1 %-8d %-8d %8d %s %2d %5s %s -> %s\n", uid, 0, length(a[5]), a[1], a[2], a[3], a[4], a[5]
}
}' 2>/dev/null
}

mcftplistfs_run ()
{
if [ -n "$MC_CONTROL_FILE" ]
then
    cat $1 | @AWK@ -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 %s\n", a[5]
}
}' 2>/dev/null > $MC_CONTROL_FILE
fi
}

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