#!/usr/bin/ruby

require "dbi"
require "csv"
require "iconv"
require "getoptlong"
require "fileutils"
require 'rubygems'
require 'active_record'
require 'redcloth'

ActiveRecord::Base.establish_connection(
    :adapter => "mysql", 
    :host => "localhost",
    :username => "root",
    :password => "w@y2G0",
    :database => "lollive");


class VendorProduct < ActiveRecord::Base
    set_table_name "vendor_product"
end

# status, size, magazine

class LG
    #    lgr.company_name, lgr.content, lgr.phone, lgr.website as web, lgc.parentId as category,
    #    CONCAT(lgm.basename,'.',lgm.format) as photo,
    #    lgm.id as media_id
    attr_reader :company, :content, :phone, :web, :category, :lPhoto, :rPhoto, :status, :size, :vendor_id

    @rowStyle0 = ""
    @rowStyle1 = ""

    @altRow = false

    def initialize(cArray)
        #company_name,content,phone,web,category,lPhoto,rPhoto)
        @company  = cArray["company_name"]
        @content  = cArray["content"]
        @phone    = fixPhone(cArray["phone"])
        @web      = fixWeb(cArray["web"])
        @category = cArray["category"]
        @size     = cArray["size"]
        @status   = cArray["status"].capitalize
        @vendor_id= cArray["vendor_id"]
        @app_hash = cArray["app_hash"]

        if !cArray["photo"].nil?
            # one photo case
            @lPhoto   = cArray["photo"]
            @lPhotoID = cArray["media_id"]
            @rPhoto   = nil
            @rPhotoID = nil
        else
            # two photo case
            @lPhoto   = cArray["photo_l"]
            @lPhotoID = cArray["medial_id"]
            @rPhoto   = cArray["photo_r"]
            @rPhotoID = cArray["mediar_id"]
        end
    end

    def leftPhoto
        "lg-" + @lPhotoID.to_s + '.tif' #getImageExtension(@lPhoto)
    end

    def realLeftPhoto
        "lg-" + @lPhotoID.to_s + getImageExtension(@lPhoto)
    end

    def rightPhoto
        if !@rPhotoID.nil? and !@rPhoto.nil?
            "lg-" + @rPhotoID.to_s + '.tif' # getImageExtension(@rPhoto)
        else
            ""
        end
    end

    def realRightPhoto
        if !@rPhotoID.nil? and !@rPhoto.nil?
            "lg-" + @rPhotoID.to_s + getImageExtension(@rPhoto)
        else
            ""
        end
    end

    def website
        fixWeb(@web)
    end

    def phoneNumber
        fixPhone(@phone)
    end

    def to_a
        [ @company, @content, self.phoneNumber, self.website, self.leftPhoto, self.rightPhoto ]
    end
    
    def q_to_a
        [ @company, self.size, @status ]
    end

    def rowStyle
        @altRow = !@altRow
        if @altRow
            @rowStyle0
        else
            @rowStyle1
        end
    end

    def size
        if @size == "double"
            "DBL"
        else
            "SGL"
        end
    end

    def photoLink(photo)
        if !photo.nil?
            pname = photo[/^.+\./] + 'jpg'
            res =  <<-EOT
<a href="/guide/lg/original/#{photo}"><img src="/guide/lg/thumb/#{pname}" border=1 /></a>
            EOT
        else
            res =  <<-EOT
<img src="/guide/lg/lg-thumb-default.jpg" border=1 />
            EOT
        end
    end

    def to_html
        rowStyle = self.rowStyle
        sz = self.size
        left  = photoLink(@lPhoto)
        right = photoLink(@rPhoto)
        if @status == "Pending"
            preview = %{<a href="/guide/load_approval/#{@app_hash}">#{@status}</a>}
        else
            preview = @status
        end

        text = <<-EOT
        <tr style='border-top: 2px solid gray;'>
            <td>
                #{sz}
            </td>
            <td>
                <strong>#{preview}</strong><br />
                <a href="#" onClick="return newWin('/devel/lg/load/#{@vendor_id}','lg',750,500);">#{@company}</a><br />
                #{@phone}<br />
                #{@web}<br />
            </td>
            <td>#{@content}</td>
            <td>#{left}</td>
            <td>#{right}</td>
        </tr>
        EOT
    end

    def linkPhotos(path)
        self.linkPhoto(path, @lPhoto, self.realLeftPhoto)
        if @rPhoto != ""
            self.linkPhoto(path, @rPhoto, self.realRightPhoto)
        end
    end

    def linkPhoto(path, orig, dest)
        retried  = false
        origPath = "/data/sites/www.landscapeonline.com/web/guide/lg/original/" 
        overPath = $override

        if !dest.nil? and !orig.nil?
            if File.exists?(overPath + dest)
                destFile = overPath + dest
            elsif File.exists?(overPath + dest[/^.+\./] + '.tif')
                destFile = overPath + dest[/^.+\./] + '.tif'
            else
                destFile = path + '/' + dest
            end

            begin
                File.link(origPath + orig, destFile)
            rescue SystemCallError
                if !retried
                    retried = true
                    File.delete(destFile)
                    retry
                end
            end
        end
    end

    def copyScaled
        retried  = false
        origPath = "/data/sites/www.landscapeonline.com/web/guide/lg/scaled/" + self.lPhoto[/^.+\./] + 'jpg' 
        destPath = "/data/sites/www.landscapeonline.com/web/products/images/prod_" + self.lPhoto[/^.+\./] + 'jpg'
        begin
            #dest[/^.+\./] + '.tif')
            FileUtils.copy(origPath, destPath)
        rescue SystemCallError
            if !retried
                retried = true
                File.delete(destPath)
                retry
            end
        end
        return 'prod_' + self.lPhoto[/^.+\./] + 'jpg'
    end
end

class LGStack
    def initialize
        @stack = Array.new
    end

    def append(lg)
        @stack.push(lg)
        self
    end

    def elements
        @stack
    end

    def dump
        p @stack
    end

    def sort(quick=false)
        if quick === false
            @stack = @stack.sort_by { |o| [ o.status, o.company ] }
        else
            @stack = @stack.sort_by { |o| [ o.company ] }
        end
    end

    def find(category)
        results = LGStack.new
        @stack.each { |elem|
            if elem.category == category
                results.append(elem)
            end
        }

        results.sort
        results
    end

    def csv_string(quick=false)
        str = ""

        CSV::Writer.generate(str) { |csv|
            @stack.each { |lg|
                if quick === false
                    csv << lg.to_a
                else
                    csv << lg.q_to_a
                end
            }
        }

        str
    end

    def export(file,quick=false)
        str = self.csv_string(quick)
        
        save = File.new(file, "w+")
        mangleEncoding("WINDOWS-1252","MAC",str).each do |line|
            save.write(line)
        end
        save.close
    end

    def linkFiles(path)
        @stack.each { |lg|
            lg.linkPhotos(path)
        }
    end
end

def connect
    DBI.connect("dbi:Mysql:lollive:localhost","root","w@y2G0")
end

def lg1Query(db,magazine,size,status, where)
    queryTemplate = <<-EOQ
    SELECT
        lg.vendor_id, lg.size,lg.status, lgr.company_name, lgr.content, lgr.phone, lgr.website as web, 
        lgc.parentId as category, lga.app_hash, CONCAT(lgm.basename,'.',lgm.format) as photo,
        lgm.id as media_id
    FROM
        lead_generator as lg
    LEFT JOIN
        lead_generator_categories as lgc ON (lg.category=lgc.id)
    LEFT JOIN
        lead_generator_approvals  as lga ON (lg.id=lga.lg_id AND lga.status = ? )
    LEFT JOIN
        lead_generator_revision   as lgr ON ( lga.rev_id=lgr.id )
    LEFT JOIN
       lead_generator_media       as lgm ON ( lgr.photos = lgm.id )
    WHERE
            lg.year   = ?
        AND
            lg.size   = ? 
        AND
            lg.magazines = ?
        AND
            lgr.id = lga.rev_id
        AND
            LOCATE(',',lgr.photos) = 0
    EOQ

    if where.nil?
        queryTemplate += <<-EO2
            ORDER BY
                lgr.company_name ASC
        EO2
    else
        queryTemplate += <<-EO3
            AND
                lgm.height #{where} lgm.width
            ORDER BY
                lgr.company_name ASC
        EO3
    end

    begin
        db.execute(queryTemplate, status, $year,  size, magazine )
    rescue DBI::DatabaseError => e
    ensure
    end
end


# retrieve approved double-2 LG's by magazine, status and category, 
def lg2Query(db,magazine,status)
    query2Template = <<-EOQ
    SELECT
        lg.vendor_id, lg.size, lg.status, lgr.company_name, lgr.content, lgr.phone, 
        lgr.website as web, lgc.parentId as category, lga.app_hash,
        CONCAT(lgm_l.basename,'.',lgm_l.format) as photo_l,
        CONCAT(lgm_r.basename,'.',lgm_r.format) as photo_r,
        lgm_l.id as medial_id,
        lgm_r.id as mediar_id
    FROM
        lead_generator as lg
    LEFT JOIN
        lead_generator_categories as lgc ON (lg.category=lgc.id)
    LEFT JOIN
        lead_generator_approvals  as lga ON (lg.id=lga.lg_id AND lga.status = ? )
    LEFT JOIN
        lead_generator_revision   as lgr ON ( lga.rev_id=lgr.id )
    LEFT JOIN
       lead_generator_media       as lgm_l ON ( LEFT(lgr.photos, LOCATE(',',lgr.photos) - 1) = lgm_l.id)
    LEFT JOIN
       lead_generator_media       as lgm_r ON ( SUBSTRING(photos FROM LOCATE(',',photos) + 1 ) = lgm_r.id)
    WHERE
            lg.year   = ?
        AND
            lg.size   = 'double' 
        AND
            lg.magazines = ?
        AND
            lgr.id = lga.rev_id
        AND
            LOCATE(',',lgr.photos) > 0
    ORDER BY
        lgr.company_name ASC
    EOQ

    begin
        db.execute(query2Template, status, $year, magazine )
    rescue DBI::DatabaseError => e
    ensure
    end
end

def getCategories(dbh,parent)
    if dbh.nil?
        return nil
    end

    query = <<-EOQ
        SELECT * FROM `lead_generator_categories`
        WHERE parentId = ?
        ORDER BY name
    EOQ

    dbh.execute(query, parent)
end

def mangleEncoding(from, to, chunk)
    pipe = IO.popen("iconv -f #{from} -t #{to}", "w+");
    chunk.each do |line|
        pipe.puts line
    end
    pipe.close_write
    pipe.readlines
end

$parentCategories = {
    1  => 'Business Services',
    2  => 'Computer Equipment',
    3  => 'Consulting',
    4  => 'Erosion Control',
    5  => 'Irrigation',
    6  => 'Lighting / Electrical',
    7  => 'Park & Recreation',
    8  => 'Pest / Wildlife Control',
    9  => 'Plant Material',
    10 => 'Plant Related Chemicals / Fertilizers',
    11 => 'Planting Accessories',
    12 => 'PMBR: Pavers, Masonry, Blocks & Rocks',
    13 => 'Site Amenities',
    14 => 'Tools & Equipment',
    15 => 'Tools For Testing',
    16 => 'Water Features'
}

def bloomPath(basePath,dir)
    if File.exist?("#{basePath}/#{dir}")
        # file exists, check if it's a dir
        if File.stat("#{basePath}/#{dir}").directory?
            return true
        end
        return false
    else
        Dir.mkdir("#{basePath}/#{dir}")
    end
end

def getImageExtension(name)
    ext = name[/\.[\w]+$/]
    if ext == ".tiff"
        return ".tif"
    end
    ext
end

def fixWeb(site)
    if !site.nil? and site.length > 4 
        if (site =~ /^http\:\/\//).nil? and (site =~ /^www\./).nil? 
            return "www." + site
        end
    end
    site
end

def fixPhone(num)
    # fix letters -> numbers
    number = num.downcase
    number.tr!('abc','2')
    number.tr!('def','3')
    number.tr!('ghi','4')
    number.tr!('jkl','5')
    number.tr!('mno','6')
    number.tr!('pqrs','7')
    number.tr!('tuv','8')
    number.tr!('wxyz','9')

    # strip all non-numerals
    number.gsub!(/\D/,'')
    b = /(\d{3})(\d{3})(\d*)/.match(number)
    "(#{b[1]}) #{b[2]}-#{b[3]}"
end

def printusage(err)
    puts <<-EOQ

    #{$0} -- extract data from the lead generator system into folders

    Usage: #{$0} report_types [options]
        --magazines, -m     magazines to dump, defaults to all
        --clear, -c         clear the contents of previous runs

    Report Types:
        --approved, -a      generate the approved folder
        --dump, -d          generate the dump folder
        --export, -e        generate vendor product listings
        --preview, -p       generate preview reports
        --report, -r        generate HTML reports
        --test, -t          generate reports into the test folder

    EOQ
    exit(err)
end

def runTest(magazines)
    basePath = $basePath + "test"
    dbh = $dbh
    date = $date

    puts
    puts "******************** [TEST] ********************"
    magazines.each { |mag|
        puts
        puts "\t******************** #{mag} ********************"
        puts

        csv = LGStack.new

        # Double, 2 Photo
        lg2Query(dbh,mag,'approved').each { |lg| csv.append(LG.new(lg)) }
        lg2Query(dbh,mag,'waiting').each { |lg| csv.append(LG.new(lg)) }

        # Double, 1 Photo
        lg1Query(dbh,mag,'double','approved',nil).each { |lg| csv.append(LG.new(lg)) }
        lg1Query(dbh,mag,'double','waiting',nil).each { |lg| csv.append(LG.new(lg)) }

        # Single, Horizontal
        lg1Query(dbh,mag,'single','approved', '<=').each { |lg| csv.append(LG.new(lg)) }
        lg1Query(dbh,mag,'single','waiting', '<=').each { |lg| csv.append(LG.new(lg)) }

        # Single, Vertical
        lg1Query(dbh,mag,'single','approved','>').each { |lg| csv.append(LG.new(lg)) }
        lg1Query(dbh,mag,'single','waiting','>').each { |lg| csv.append(LG.new(lg)) }

        # iterate over the categories in the stack
        $parentCategories.each { |id,val|
            puts "\t\t  #{val}"
            path  = mag + '/' + val.gsub(/[\s\:\&\,\/]+/,'_') # directory name
            bloomPath(basePath,path)
            stack = csv.find(id)
            stack.export(basePath + '/' + path + '/raw-' + date + '.csv')
            stack.linkFiles(basePath + '/' + path)
        }
    }
end

def runApproved(magazines)
    basePath = $basePath + "approved"
    dbh = $dbh
    date = $date

    puts
    puts "******************** [APPROVED] ********************"
    magazines.each { |mag|
        puts
        puts "\t******************** #{mag} ********************"
        puts

        dbls2 = LGStack.new
        dbls1 = LGStack.new
        sglsh = LGStack.new
        sglsv = LGStack.new

        # Double, 2 Photo
        lg2Query(dbh,mag,'approved').each { |lg| dbls2.append(LG.new(lg)) }
        lg2Query(dbh,mag,'waiting').each { |lg| dbls2.append(LG.new(lg)) }

        # Double, 1 Photo
        lg1Query(dbh,mag,'double','approved',nil).each { |lg| dbls1.append(LG.new(lg)) }
        lg1Query(dbh,mag,'double','waiting',nil).each { |lg| dbls1.append(LG.new(lg)) }

        # Single, Horizontal
        lg1Query(dbh,mag,'single','approved', '<=').each { |lg| sglsh.append(LG.new(lg)) }
        lg1Query(dbh,mag,'single','waiting', '<=').each { |lg| sglsh.append(LG.new(lg)) }

        # Single, Vertical
        lg1Query(dbh,mag,'single','approved','>').each { |lg| sglsv.append(LG.new(lg)) }
        lg1Query(dbh,mag,'single','waiting','>').each { |lg| sglsv.append(LG.new(lg)) }

        # iterate over the categories in the stack
        $parentCategories.each { |id,val|
            puts "\t\t  #{val}"
            path  = mag + '/' + val.gsub(/[\s\:\&\,\/]+/,'_') # directory name
            bloomPath(basePath,path)

            stack = dbls2.find(id)
            stack.export(basePath + '/' + path + '/dbls2-' + date + '.csv')
            stack.linkFiles(basePath + '/' + path)

            stack = dbls1.find(id)
            stack.export(basePath + '/' + path + '/dbls1-' + date + '.csv')
            stack.linkFiles(basePath + '/' + path)

            stack = sglsh.find(id)
            stack.export(basePath + '/' + path + '/sglsh-' + date + '.csv')
            stack.linkFiles(basePath + '/' + path)

            stack = sglsv.find(id)
            stack.export(basePath + '/' + path + '/sglsv-' + date + '.csv')
            stack.linkFiles(basePath + '/' + path)
        }
    }
end

def runDump(magazines)
    path = $basePath + "dump"
end

def runPreview(magazines)
    basePath = $basePath + "preview"
    dbh = $dbh
    date = $date

    puts
    puts "******************** [PREVIEW] ********************"
    magazines.each { |mag|
        puts
        puts "\t******************** #{mag} ********************"
        puts

        dbls2 = LGStack.new
        other = LGStack.new

        # Double, 2 Photo
        lg2Query(dbh,mag,'approved').each { |lg| dbls2.append(LG.new(lg)) }
        lg2Query(dbh,mag,'waiting').each { |lg| dbls2.append(LG.new(lg)) }

        # Double, 1 Photo
        lg1Query(dbh,mag,'double','approved',nil).each { |lg| other.append(LG.new(lg)) }
        lg1Query(dbh,mag,'double','waiting',nil).each { |lg| other.append(LG.new(lg)) }

        # Single, Horizontal
        lg1Query(dbh,mag,'single','approved', '<=').each { |lg| other.append(LG.new(lg)) }
        lg1Query(dbh,mag,'single','waiting', '<=').each { |lg| other.append(LG.new(lg)) }

        # Single, Vertical
        lg1Query(dbh,mag,'single','approved','>').each { |lg| other.append(LG.new(lg)) }
        lg1Query(dbh,mag,'single','waiting','>').each { |lg| other.append(LG.new(lg)) }

        # iterate over the categories in the stack
        $parentCategories.each { |id,val|
            puts "\t\t  #{val}"
            path  = mag + '/' + val.gsub(/[\s\:\&\,\/]+/,'_') # directory name

            stack = dbls2.find(id)
            stack.export(basePath + '/' + path + '/dbls2-' + date + '.csv')
            stack.linkFiles(basePath + '/' + path)

            stack = other.find(id)
            stack.export(basePath + '/' + path + '/other-' + date + '.csv')
            stack.linkFiles(basePath + '/' + path)
        }
    }
end

def runQuick(magazines)
    basePath = $basePath + "quick"
    dbh = $dbh
    date = $date

    puts
    puts "******************** [QUICK] ********************"
    magazines.each { |mag|
        puts
        puts "\t******************** #{mag} ********************"
        puts

        csv = LGStack.new

        # Double, 2 Photo
        lg2Query(dbh,mag,'approved').each { |lg| csv.append(LG.new(lg)) }
        lg2Query(dbh,mag,'waiting').each { |lg| csv.append(LG.new(lg)) }

        # Double, 1 Photo
        lg1Query(dbh,mag,'double','approved',nil).each { |lg| csv.append(LG.new(lg)) }
        lg1Query(dbh,mag,'double','waiting',nil).each { |lg| csv.append(LG.new(lg)) }

        # Single, Horizontal
        lg1Query(dbh,mag,'single','approved', '<=').each { |lg| csv.append(LG.new(lg)) }
        lg1Query(dbh,mag,'single','waiting', '<=').each { |lg| csv.append(LG.new(lg)) }

        # Single, Vertical
        lg1Query(dbh,mag,'single','approved','>').each { |lg| csv.append(LG.new(lg)) }
        lg1Query(dbh,mag,'single','waiting','>').each { |lg| csv.append(LG.new(lg)) }

        csv.sort(true)
        csv.export(basePath + '/' +  mag + '/quick-' + date + '.csv',true)

    }
end
    

def runReport(magazines)
    basePath = "/data/sites/www.landscapeonline.com/web/guide/reports/"
    dbh = $dbh
    date = $date

    magazines.each { |mag|
        
        save = File.new(basePath + mag + ".html", "w+")
        save.write <<-EOH
    <html>
        <head>
            <title>#{mag.upcase} LG Report :: #{$date}</title>
            <script language="JavaScript">
            function newWin(url,id,width,height) {
                window.open(url,id,'toolbar=0,location=0,directories=0,status=0,menubar=0,resizable=1,width='+ width+',height='+ height +',scrollbars=yes');
                return false;
            }
            </script>
        </head>
        <body>
        EOH
        save.write "<h1>#{mag.upcase} LG Report :: #{$date}</h1>"
        save.write "<ul> "
        $parentCategories.sort.each { |id,val|
            save.write %{<li><a href="##{id}">#{val}</a></li>} 
        }
        save.write "</ul> "

        csv = LGStack.new

        # Double, 2 Photo
        lg2Query(dbh,mag,'approved').each { |lg| csv.append(LG.new(lg)) }
        lg2Query(dbh,mag,'waiting').each { |lg| csv.append(LG.new(lg)) }

        # Double, 1 Photo
        lg1Query(dbh,mag,'double','approved',nil).each { |lg| csv.append(LG.new(lg)) }
        lg1Query(dbh,mag,'double','waiting',nil).each { |lg| csv.append(LG.new(lg)) }

        # Single, Horizontal
        lg1Query(dbh,mag,'single','approved', '<=').each { |lg| csv.append(LG.new(lg)) }
        lg1Query(dbh,mag,'single','waiting', '<=').each { |lg| csv.append(LG.new(lg)) }

        # Single, Vertical
        lg1Query(dbh,mag,'single','approved','>').each { |lg| csv.append(LG.new(lg)) }
        lg1Query(dbh,mag,'single','waiting','>').each { |lg| csv.append(LG.new(lg)) }

        # iterate over the categories in the stack
        $parentCategories.sort.each { |id,val|
            save.write <<-EOQ
            <h2 id="#{id}">#{val}</h2>
            <hr noshade size="-1" />
            <table width="100%" border="1" cellpadding="5" cellspacing="5">
            EOQ
            path  = mag + '/' + val.gsub(/[\s\:\&\,\/]+/,'_') # directory name
            stack = csv.find(id)
            stack.elements.each { |lg|
                save.write lg.to_html
            }
            save.write %{
            </table>
            }
        }

        save.write <<-EOH
        </body>
    </html>
        EOH

        save.close
    }
end

def runExport(magazines)
    basePath = "/data/sites/www.landscapeonline.com/web/guide/reports/"
    dbh = $dbh
    date = $date

    magazines.each { |mag|
        csv = LGStack.new

        # Double, 2 Photo
        lg2Query(dbh,mag,'approved').each { |lg| csv.append(LG.new(lg)) }

        # Double, 1 Photo
        lg1Query(dbh,mag,'double','approved',nil).each { |lg| csv.append(LG.new(lg)) }

        # Single, Horizontal
        lg1Query(dbh,mag,'single','approved', '<=').each { |lg| csv.append(LG.new(lg)) }

        # Single, Vertical
        lg1Query(dbh,mag,'single','approved','>').each { |lg| csv.append(LG.new(lg)) }

        csv.elements.each { |elem|
            # copy image
            # create record
            v = VendorProduct.new
            v.imported = true
            v.vendor_id = elem.vendor_id
            v.product_name = elem.company
            v.description  = elem.content
            v.photo = elem.copyScaled
            v.save
            #p v.inspect
        }
    }
end


#### Define Constants
version = "0.2.0"
required_opts = 0
clear_old = false
reports   = []
magazines = ['lasn','lcn','lsmp']
$year     = 2008
$basePath = "/data/sites/lead_generators/#{$year}/"
$override = "/data/sites/lead_generators/image_override/"

opts = GetoptLong.new(
    # long, short, required
    [ "--approved", "-a", GetoptLong::NO_ARGUMENT ],
    [ "--dump", "-d", GetoptLong::NO_ARGUMENT ],
    [ "--export", "-e", GetoptLong::NO_ARGUMENT ],
    [ "--report", "-r", GetoptLong::NO_ARGUMENT ],
    [ "--preview", "-p", GetoptLong::NO_ARGUMENT ],
    [ "--quick", "-q", GetoptLong::NO_ARGUMENT ],
    [ "--test", "-t", GetoptLong::NO_ARGUMENT ],
    [ "--clear", "-c", GetoptLong::NO_ARGUMENT ],
    [ "--magazines", "-m", GetoptLong::REQUIRED_ARGUMENT ],
    [ "--version", "-v", GetoptLong::NO_ARGUMENT ]
)

opts.each { |option, arg|
    case option
        when "--clear"
            clear_old = true
        when "--version"
            puts "#{$0}, Version #{version}"
            exit(0)
        when "--approved"
            required_opts += 1
            reports << 'approved'
        when "--dump"
            required_opts += 1
            reports << 'dump'
        when "--report"
            required_opts += 1
            reports << 'report'
        when "--preview"
            required_opts += 1
            reports << 'preview'
        when "--quick"
            required_opts += 1
            reports << 'quick'
        when "--test"
            required_opts += 1
            reports << 'test'
        when "--magazines"
            # find which magazines we're going to go over
            magazines  = arg.split(',').delete_if { |m| !magazines.include?(m) }
        when "--export"
            # export active lgs to vendor area
            required_opts += 1
            reports << 'export'
    end
}

if required_opts == 0
    printusage(0)
end

$dbh     = connect
$date    = Date.today.to_s

if clear_old
    magazines.each { |m|
    }
end

reports.each { |r|
    case r
        when "approved"
            runApproved(magazines)
        when "dump"
            runDump(magazines)
        when "preview"
            runPreview(magazines)
        when "quick"
            runQuick(magazines)
        when "test"
            runTest(magazines)
        when "report"
            runReport(magazines)
        when "export"
            runExport(magazines)
    end
}

exit(0)
