#!/usr/bin/env ruby
require 'ftools'

mydirs = %w( /opt/lexis /opt/lexis/sbin /opt/lexis/bin /opt/lexis/lib /opt/lexis/lib/lexis /var/lexis)
sysdirs = %w( /etc/init.d /usr/local/bin )

client_files = []
server_files = []

def log(msg)
    $stderr.puts "Lexis install: #{msg}"
end
def install(file, where, mode=0755)
    dest = where
    dest = File.join(where,file) if File.directory?(DESTDIR + where)
    log "cp #{file} -> #{dest}"
    File.copy file, DESTDIR + dest
    File.chmod mode, DESTDIR + dest
    dest
end

def installsl(source,dest)
    log "ln #{dest} -> #{source}"
    File.symlink source, DESTDIR + dest
    dest
end

DESTDIR = ARGV[0]
DESTDIR ||= ''
unless File.directory? DESTDIR
    $stderr.puts "#{DESTDIR} - no such directory"
    exit 1
end
log "Installing to #{DESTDIR}"

log "Creating directories:"
(mydirs + sysdirs).each do
    |inst_dir|
    path = DESTDIR
    inst_dir.split('/').each do
        |dir|
        path = File.join(path, dir)
        Dir.mkdir path, 0755 unless File.exists? path
        exit 1 unless File.exists? path
    end
    log "Created #{path}"
end

File.chmod 0750, DESTDIR + '/var/lexis'

#client
if Dir.chdir 'client'
    client_files << install('rclexis', '/etc/init.d/lexis')
    %w( lexis_active lexis_warning lexis_warning.rb ).each do
        |file|
        log "Client file: #{file}"
        rpmfile = install(file,'/opt/lexis/bin')
        client_files << rpmfile
        client_files << installsl(rpmfile, '/usr/local/bin/' + file)
    end
    Dir.chdir '..'
end

if Dir.chdir 'server'
    %w( glexis lexis_who lexis_extract ).each do
        |file|
        sfile =  install(file, '/opt/lexis/sbin')
        server_files << sfile
        log "Server file: #{sfile}"
    end

    install('key', '/opt/lexis/lib') # explicitly included in %files in spec file
    %w( lexis.glade lexis.rb lexis/client.rb lexis/cmd.rb).each do
        |file|
        sfile = install(file, '/opt/lexis/lib')
        server_files << sfile
        log "Server file: #{sfile}"
    end
    Dir.chdir '..'
end

File.open('client.lst','w') do
    |fh|
    client_files.each do
        |filename|
        fh.puts filename
    end
end
File.open('server.lst','w') do
    |fh|
    server_files.each do
        |filename|
        fh.puts filename
    end
end

