#!/usr/bin/env ruby
require 'versionomy'
require 'colorize'
require 'pry'
class String; def to_version; Versionomy.parse(self) end end

HOME=ENV['HOME']
APP_ROOT="#{HOME}/Documents/workspace/mozo"
APP_ASSET_ROOT="#{APP_ROOT}/www/assets"
app_config_path = File.join(APP_ROOT, 'config.xml')
app_config = File.read(app_config_path)
app_index_html_path = File.join(APP_ROOT, 'www/index.html')
app_index_html = File.read(app_index_html_path)
current_version = app_config.match(/version="([\.\d]+)"/)[1].to_version
new_version = File.read("config/version").strip.to_version
version_increased = false
while new_version <= current_version
  version_increased = true
  new_version = new_version.bump(:tiny)
end
if version_increased
  puts "Increasing version value to #{new_version}".colorize(:red)
  File.open("config/version", 'w+'){|f| f.puts new_version.to_s }
end

`spring stop`
`rm -rf #{APP_ASSET_ROOT}`
`mkdir #{APP_ASSET_ROOT}`
`rm -rf public/assets`
`QWAITER_MOBILE_EXPORT=yes RAILS_ENV=user_app bundle exec rake assets:precompile`
`find public/assets -name "*.gz" -exec rm -f {} \\;`
`./bin/dedigest_assets`

# correct stuff
`./bin/user_asset_corrections`

# now move stuff to a cleaned up cordova location
`cp -r public/assets/user #{APP_ASSET_ROOT}/user`
`cp -r public/assets/theme1 #{APP_ASSET_ROOT}/theme1`
`cp -r public/assets/vendor #{APP_ASSET_ROOT}/vendor`

# Theme1 files are not used
`find #{APP_ASSET_ROOT}/theme1 -name "*.css" -exec rm -f {} \\;`
`find #{APP_ASSET_ROOT}/theme1 -name "*.js" -exec rm -f {} \\;`

# copy font files
`find public/assets -iname "font*" -depth 1 -exec cp {} #{APP_ASSET_ROOT} \\;`

# rm -rf public/assets/cmtool;
# rm -rf public/assets/jquery-ui;
# rm -rf public/assets/admin;
# rm -rf public/assets/waiter;
# rm -rf public/assets/obtain_token;
# rm -rf public/assets/qr_sheet;
# rm -rf public/assets/supplier;
# rm -rf public/assets/site;
# rm -rf public/assets/cartoon;
# rm -rf public/assets/frames;
# QWAITER_MOBILE_EXPORT=yes RAILS_ENV=user_app TEST_HOST=$1 bundle exec rails runner bin/build_mobile_app.rb;
`rm -rf public/assets`

# Set app versions
File.open(app_config_path, 'w+'){|f| f.puts app_config.sub(%[version="#{current_version}"], %[version="#{new_version}"])}
File.open(app_index_html_path, 'w+'){ |f| f.puts app_index_html.sub(/$app_version\s*=\s*'([\.\d]+)'/, "$app_version = '#{new_version.to_s}'") }
