#!/usr/local/bin/kermit
;
; f t p s y n c d o w n
;
; Synchronizes a local directory from a directory on an FTP server.
;  . Server files that don't exist locally are downloaded.
;  . Server files that exist locally are downloaded only if newer.
;  . Local files that don't exist on the server are deleted.
;  . Server file timestamps are preserved (if server supports MDTM).
;  . Server file permissions are not preserved (FTP doesn't allow that).
;  . Ditto for file owner, group, ACLs, etc.
;  . Works across platforms via automatic text/binary mode switching.
;  . Works quietly but keeps a log of what it did.
;
; Recursive directory tree synchronization can be done too, if the
; server supports it.  Simply add "/recursive" to the mget command
; and change the "\ffiles()" invocation to "\frfiles()".
; 
; Requires: C-Kermit 80 or later or K95 2.0 or later
;
; F. da Cruz, Columbia University, 24 Feb 2003

; Parameters - Change as needed (or turn them into arguments)

.host = kermit.columbia.edu         ; Change to desired host
.rdirectory = kermit/g              ; Change to desired host directory
.ldirectory = ~/g                   ; Change to desired local directory
.logfile := \v(home)ftpsync.log     ; Change to desired logfile name

; End of parameter defintions.

set transaction-log brief           ; Choose brief transaction-log format
set exit warning off                ; No "OK to exit?" prompts
set quiet on                        ; Suppress progress messages

lcd \m(ldirectory)                  ; CD to desired local directory
if fail exit 1 "LCD failed - \m(ldirectory)" ; Make sure we did

ftp open \m(host) /anonymous        ; Open and check anonymous FTP connection
if fail exit 1 Login failed
if not \v(ftp_loggedin) exit 1 "Anonymous Login failed"

log transactions \m(logfile)        ; Start log

ftp cd \m(rdirectory)               ; CD to desired server directory
if fail exit 1 "FTP CD failed - \m(rdirectory)"

ftp mget /collision:overwrite /update * ; Get all server files in update mode
if fail exit 1 "Mget failed"            ; Check for errors

; Remove extraneous local files

for \%i 1 \ffiles(*,&a) 1 {         ; Loop through local files
    ftp check \&a[\%i]              ; Does file exist on server
    if fail {                       ; Yes - delete it
        ldelete \&a[\%i]
        if fail exit 1 Ldelete \&a[\%i] failed
        writeln transaction-log "\v(ndate),\v(time),DELETED,\&a[\%i]"
    }
}
bye                                 ; Disconnect from server
close transaction-log               ; Close log
cat \m(logfile)                     ; Display log
exit 0
