#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

$lib = File.expand_path('../lib', File.dirname(__FILE__))
$LOAD_PATH.unshift($lib)

require "ZAPKDownloader"
require "optparse"

class Main
    
    attr_accessor :downloader

    def initialize

        ARGV << '-h' if ARGV.empty?

        inputServiceAccount = nil
        inputOutputFilePath = "."
        inputOutputFileName = "Universal.apk"
        inputPackageName = nil
        inputVersionCode = nil
        OptionParser.new do |opts|
            opts.banner = "Usage: ZAPKDownloader [options]"
            opts.on('-s', '--serviceAccount SERVICEACCOUNT', 'xxxx@xxx.iam.gserviceaccount.com.json') do |serviceAccount|
                inputServiceAccount = serviceAccount
            end 

            opts.on('-p', '--path OUTPUT_FILEPATH', '/Users/zhgchgli/Downloads') do |filePath|
                inputOutputFilePath = filePath
            end

            opts.on('-f', '--fileName OUTPUT_FILENAME', 'zhgchg.apk') do |fileName|
                inputOutputFileName = fileName
            end

            opts.on('-n', '--packageName PACKAGENAME', 'com.zhgchg') do |packageName|
                inputPackageName = packageName
            end

            opts.on('-v', '--versionCode VERSIONCODE', '1203') do |versionCode|
                inputVersionCode = versionCode
            end
        end.parse!
        

        if inputServiceAccount.nil? 
            puts "please specify your service account json auth file. e.g. -f xxxx@xxx.iam.gserviceaccount.com.json"
            return
        end

        if inputPackageName.nil? 
            puts "please specify your android app package name. e.g. -n com.zhgchg"
            return
        end

        if inputVersionCode.nil? 
            puts "please specify your android app's version code that you want to download. e.g. -v 1203"
            return
        end

        @downloader = ZAPKDownloader.new(inputServiceAccount, ["https://www.googleapis.com/auth/androidpublisher"])
        fileFullPath = "#{inputOutputFilePath}/#{inputOutputFileName}"

        downloader.download_generated_universal_apk(inputPackageName, inputVersionCode, fileFullPath)
    end
end

Main.new()
