#!/bin/sh

# written by Maciej 'YTM/Alliance' Witkowiak
# ytm@friko.onet.pl
# 14.09.1999

# BAD THINGS:
# - copyout changes BIG letters and '_' to "?" - multiple matches possible

# TODO:
# - how to copyout files with '_' instead of spaces? (change '_' into '?'? - will it work?)
# - d64_list seems to be buggy <- c1541 fault!
# - better code indentation ???
# - copyin gives chmod error (what to do?)

# Command functions
d64_list ()
{
  c1541 -attach $1 -list | awk '
	BEGIN { flag=0; }
   { if ($1=="VDrive:" || ( $1=="0" && substr($2,1,1)=="." ) || $3=="free.") next
 	  else
       {
	curname=substr($0,index($0,"\042")+1)
	curname=substr(curname,1,index(curname,"\042")-1)
	gsub ("\040","_",curname)
	if (substr($NF,3,3)=="<") prot="-r--r--r--";  else prot="-rw-rw-rw-"
	printf("%s   1 root     root %12d Jan  1 12:00 %s\n",prot,$1*254,curname)
       }
   } 
 '
}

d64_copyout ()
# $1 is the archive name
# $2 is a name of a file within the archive
# $3 is a name of a file within the system (to add from or extract to)
{

echo -e $1 '\n' $2 '\n' $3 | awk '
		  { 
		  	 name=sprintf("attach %s \n",$0)
			 getline;
			 gsub("[A-Z]|_","?",$0)
			 name=sprintf("%sread%s",name,$0)
			 getline;
			 name=sprintf("%s%s",name,substr($0,2))
			 print name
		   }

' | c1541 > /dev/null

}

d64_copyin ()
# $1 is the archive name
# $2 is a name of a file within the archive
# $3 is a name of a file within the system (to add from or extract to)
{
  c1541 -attach $1 -write $3 $2 >/dev/null
}

# Command line parser
# $1 is the command
# $2 is the archive name
# $3 is a name of a file within the archive
# $4 is a name of a file within the system (to add from or extract to)
case "$1" in
   list)    d64_list $2;          exit $?;;
   copyout) d64_copyout $2 $3 $4; exit $?;;
   copyin)  d64_copyin $2 $3 $4;  exit $?;;
esac
# Show an error if this was called with some other command
exit 1
