Skip to content
This repository
tree: e5bd9458aa
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 1684 lines (1366 sloc) 55.11 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
#------------------------------------------------------------------------
# (The MIT License)
#
# Copyright (c) 2008-2011 Rhomobile, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# http://rhomobile.com
#------------------------------------------------------------------------

require 'find'
require 'erb'
#require 'rdoc/task'
require 'digest/sha2'
require 'rexml/document'

#Look, another big fat hack. Make it so we can remove tasks from rake -T by setting comment to nil
module Rake
  class Task
    attr_accessor :comment
  end
end

$app_basedir = pwd
chdir File.dirname(__FILE__)

require File.join(pwd, 'lib/build/jake.rb')

load File.join(pwd, 'platform/bb/build/bb.rake')
load File.join(pwd, 'platform/android/build/android.rake')
load File.join(pwd, 'platform/iphone/rbuild/iphone.rake')
load File.join(pwd, 'platform/wm/build/wm.rake')
load File.join(pwd, 'platform/linux/tasks/linux.rake')
load File.join(pwd, 'platform/wp7/build/wp.rake')
load File.join(pwd, 'platform/symbian/build/symbian.rake')
load File.join(pwd, 'platform/osx/build/osx.rake')

def get_dir_hash(dir, init = nil)
  hash = init
  hash = Digest::SHA2.new if hash.nil?
  Dir.glob(dir + "/**/*").each do |f|
    hash << f
    hash.file(f) if File.file? f
  end
  hash
end

namespace "framework" do
  task :spec do
    loadpath = $LOAD_PATH.inject("") { |load_path,pe| load_path += " -I" + pe }

    rhoruby = ""

    if RUBY_PLATFORM =~ /(win|w)32$/
      rhoruby = 'res\\build-tools\\RhoRuby'
    elsif RUBY_PLATFORM =~ /darwin/
      rhoruby = 'res/build-tools/RubyMac'
    else
      rhoruby = 'res/build-tools/rubylinux'
    end
   
    puts `#{rhoruby} -I#{File.expand_path('spec/framework_spec/app/')} -I#{File.expand_path('lib/framework')} -I#{File.expand_path('lib/test')} -Clib/test framework_test.rb`
  end
end


$application_build_configs_keys = ['security_token', 'encrypt_database', 'android_title', 'iphone_db_in_approot', 'iphone_set_approot', 'iphone_userpath_in_approot', "motorola_license", "motorola_license_company"]

def make_application_build_config_header_file
  f = StringIO.new("", "w+")
  f.puts "// WARNING! THIS FILE IS GENERATED AUTOMATICALLY! DO NOT EDIT IT MANUALLY!"
  #f.puts "// Generated #{Time.now.to_s}"
  f.puts ""
  f.puts "#include <string.h>"
  f.puts ""
  f.puts '#include "app_build_configs.h"'
  if $rhosimulator_build
    f.puts '#include "common/RhoSimConf.h"'
  end
  f.puts ""
      
  f.puts 'static const char* keys[] = { ""'
  $application_build_configs.keys.each do |key|
    f.puts ',"'+key+'"'
  end
  f.puts '};'
  f.puts ''
  
  count = 1

  f.puts 'static const char* values[] = { ""'
  $application_build_configs.keys.each do |key|
    f.puts ',"'+$application_build_configs[key].to_s().gsub('\\', "\\\\\\")+'"'
    count = count + 1
  end
  f.puts '};'
  f.puts ''

  f.puts '#define APP_BUILD_CONFIG_COUNT '+count.to_s
  f.puts ''
  f.puts 'const char* get_app_build_config_item(const char* key) {'
  f.puts ' int i;'
  if $rhosimulator_build
    f.puts ' if (strcmp(key, "security_token") == 0) {'
    f.puts ' return rho_simconf_getString("security_token");'
    f.puts ' }'
  end
  f.puts ' for (i = 1; i < APP_BUILD_CONFIG_COUNT; i++) {'
  f.puts ' if (strcmp(key, keys[i]) == 0) {'
  f.puts ' return values[i];'
  f.puts ' }'
  f.puts ' }'
  f.puts ' return 0;'
  f.puts '}'
  f.puts ''
  
  Jake.modify_file_if_content_changed(File.join($startdir, "platform", "shared", "common", "app_build_configs.c"), f)
  
end

def make_application_build_capabilities_header_file
  f = StringIO.new("", "w+")
  f.puts "// WARNING! THIS FILE IS GENERATED AUTOMATICALLY! DO NOT EDIT IT MANUALLY!"
  #f.puts "// Generated #{Time.now.to_s}"
  f.puts ""

  caps = []
 
  capabilities = $app_config["capabilities"]

  if capabilities != nil && capabilities.is_a?(Array)
     capabilities.each do |cap|
        caps << cap
     end
  end

  caps.sort.each do |cap|
     f.puts '#define APP_BUILD_CAPABILITY_'+cap.upcase
  end

  f.puts ''
  
  Jake.modify_file_if_content_changed(File.join($startdir, "platform", "shared", "common", "app_build_capabilities.h"), f)
end

def make_application_build_config_java_file

    f = StringIO.new("", "w+")
    f.puts "// WARNING! THIS FILE IS GENERATED AUTOMATICALLY! DO NOT EDIT IT MANUALLY!"
    #f.puts "// Generated #{Time.now.to_s}"

    f.puts "package com.rho;"
    f.puts ""
    f.puts "public class AppBuildConfig {"

    f.puts 'static final String keys[] = { ""'
    $application_build_configs.keys.each do |key|
      f.puts ',"'+key+'"'
    end
    f.puts '};'
    f.puts ''

    count = 1

    f.puts 'static final String values[] = { ""'
    $application_build_configs.keys.each do |key|
      f.puts ',"'+$application_build_configs[key]+'"'
      count = count + 1
    end
    f.puts '};'
    f.puts ''

    f.puts 'static final int APP_BUILD_CONFIG_COUNT = '+count.to_s + ';'
    f.puts ''
    f.puts 'public static String getItem(String key){'
    f.puts ' for (int i = 1; i < APP_BUILD_CONFIG_COUNT; i++) {'
    f.puts ' if ( key.compareTo( keys[i]) == 0) {'
    f.puts ' return values[i];'
    f.puts ' }'
    f.puts ' }'
    f.puts ' return null;'
    f.puts '}'
    f.puts "}"

    Jake.modify_file_if_content_changed( File.join( $startdir, "platform/bb/RubyVM/src/com/rho/AppBuildConfig.java" ), f )
end

def update_rhoprofiler_java_file
    use_profiler = $app_config['profiler'] || ($app_config[$current_platform] && $app_config[$current_platform]['profiler'])
    
    content = ""
    File.open( File.join( $startdir, "platform/bb/RubyVM/src/com/rho/RhoProfiler.java" ), 'rb' ){ |f| content = f.read() }
    is_find = nil

    if use_profiler
        is_find = content.sub!( 'RHO_STRIP_PROFILER = true;', 'RHO_STRIP_PROFILER = false;' )
    else
        is_find = content.sub!( 'RHO_STRIP_PROFILER = false;', 'RHO_STRIP_PROFILER = true;' )
    end
    
    if is_find
        puts "RhoProfiler.java has been modified: RhoProfiler is " + (use_profiler ? "enabled!" : "disabled!")
        File.open( File.join( $startdir, "platform/bb/RubyVM/src/com/rho/RhoProfiler.java" ), 'wb' ){ |f| f.write(content) }
    end

end

def update_rhodefs_header_file
    use_profiler = $app_config['profiler'] || ($app_config[$current_platform] && $app_config[$current_platform]['profiler'])
    
    content = ""
    File.open( File.join( $startdir, "platform/shared/common/RhoDefs.h" ), 'rb' ){ |f| content = f.read() }
    is_find = nil

    if use_profiler
        is_find = content.sub!( '#define RHO_STRIP_PROFILER 1', '#define RHO_STRIP_PROFILER 0' )
    else
        is_find = content.sub!( '#define RHO_STRIP_PROFILER 0', '#define RHO_STRIP_PROFILER 1' )
    end
    
    if is_find
        puts "RhoDefs.h has been modified: RhoProfiler is " + (use_profiler ? "enabled!" : "disabled!")
        File.open( File.join( $startdir, "platform/shared/common/RhoDefs.h" ), 'wb' ){ |f| f.write(content) }
    end
end

namespace "config" do
  task :common do
    $startdir = File.dirname(__FILE__)
    $startdir.gsub!('\\', '/')
    
    $binextensions = []
    buildyml = 'rhobuild.yml'

    buildyml = ENV["RHOBUILD"] unless ENV["RHOBUILD"].nil?
    $config = Jake.config(File.open(buildyml))
    $config["platform"] = $current_platform if $current_platform
    
    if RUBY_PLATFORM =~ /(win|w)32$/
      $all_files_mask = "*.*"
      $rubypath = "res/build-tools/RhoRuby.exe"
    else
      $all_files_mask = "*"
      if RUBY_PLATFORM =~ /darwin/
        $rubypath = "res/build-tools/RubyMac"
      else
        $rubypath = "res/build-tools/rubylinux"
      end
    end

    if $app_path.nil? #if we are called from the rakefile directly, this wont be set
      #load the apps path and config

      $app_path = $config["env"]["app"]
      unless File.exists? $app_path
        puts "Could not find rhodes application. Please verify your application setting in #{File.dirname(__FILE__)}/rhobuild.yml"
        exit 1
      end
    end

    ENV["ROOT_PATH"] = $app_path.to_s + '/app/'
    ENV["APP_TYPE"] = "rhodes"

    $app_config = Jake.config(File.open(File.join($app_path, "build.yml")))

    Jake.set_bbver($app_config["bbver"].to_s)
    
    extpaths = []

    if $app_config["paths"] and $app_config["paths"]["extensions"]
      if $app_config["paths"]["extensions"].is_a? String
        extpaths << $app_config["paths"]["extensions"]
      elsif $app_config["paths"]["extensions"].is_a? Array
        extpaths += $app_config["paths"]["extensions"]
      end
    end
    extpaths << $config["env"]["paths"]["extensions"] if $config["env"]["paths"]["extensions"]
    extpaths << File.join($app_path, "extensions")
    extpaths << File.join($startdir, "lib","extensions")
    $app_config["extpaths"] = extpaths
    
    if $app_config["build"] and $app_config["build"] == "release"
      $debug = false
    else
      $debug = true
    end
    
    extensions = []
    extensions += $app_config["extensions"] if $app_config["extensions"] and
       $app_config["extensions"].is_a? Array
    extensions += $app_config[$config["platform"]]["extensions"] if $app_config[$config["platform"]] and
       $app_config[$config["platform"]]["extensions"] and $app_config[$config["platform"]]["extensions"].is_a? Array
    extensions += get_extensions
    $app_config["extensions"] = extensions.uniq
    
    capabilities = []
    capabilities += $app_config["capabilities"] if $app_config["capabilities"] and
       $app_config["capabilities"].is_a? Array
    capabilities += $app_config[$config["platform"]]["capabilities"] if $app_config[$config["platform"]] and
       $app_config[$config["platform"]]["capabilities"] and $app_config[$config["platform"]]["capabilities"].is_a? Array
    $app_config["capabilities"] = capabilities

    application_build_configs = {}

    #Process rhoelements settings
    if $current_platform == "wm" || $current_platform == "android"
        if $app_config["app_type"] == 'rhoelements'
        
            if !$app_config["capabilities"].index('non_motorola_device')
                $app_config["capabilities"] += ["motorola"] unless $app_config["capabilities"].index("motorola")
                $app_config["extensions"] += ["rhoelementsext"]
                $app_config["extensions"] += ["motoapi"] #extension with plug-ins
                
                #check for RE2 plugins
                plugins = ""
                $app_config["extensions"].each do |ext|
                    if ( ext.start_with?('moto-') )
                        plugins += ',' if plugins.length() > 0
                        plugins += ext[5, ext.length()-5]
                    end
                end
                
                if plugins.length() == 0
                    plugins = "ALL"
                end
                
                application_build_configs['moto-plugins'] = plugins if plugins.length() > 0
                
            end
            
            if !$app_config["capabilities"].index('native_browser')
                $app_config["capabilities"] += ["motorola_browser"] unless $app_config["capabilities"].index('motorola_browser')
            end
        end

        application_build_configs['shared-runtime'] = '1' if $app_config["capabilities"].index('shared_runtime')

        if $app_config["capabilities"].index("motorola_browser")
            $app_config['extensions'] += ['webkit-browser'] unless $app_config['extensions'].index('webkit-browser')
        end
        
        if $app_config["extensions"].index("webkit-browser")
            $app_config["capabilities"] += ["webkit_browser"]
            $app_config["extensions"].delete("webkit-browser")
        end
        
        if $app_config["capabilities"].index("webkit_browser") || $app_config["capabilities"].index("motorola")
            #contains wm code for webkit browser support
            $app_config["extensions"] += ["rhoelements"] unless $app_config['extensions'].index('rhoelements')
        end
    end

    $hidden_app = $app_config["hidden_app"].nil?() ? "0" : $app_config["hidden_app"]
    
    #application build configs

    $application_build_configs_keys.each do |key|
      value = $app_config[key]
      if $app_config[$config["platform"]] != nil
        if $app_config[$config["platform"]][key] != nil
          value = $app_config[$config["platform"]][key]
        end
      end
      if value != nil
        application_build_configs[key] = value
      end
    end
    $application_build_configs = application_build_configs
    #check for rhoelements gem
    $rhoelements_features = ""
    if $app_config['extensions'].index('barcode')
        #$app_config['extensions'].delete('barcode')
        $rhoelements_features += "- Barcode extension\n"
    end
    if $app_config['extensions'].index('nfc')
        #$app_config['extensions'].delete('nfc')
        $rhoelements_features += "- NFC extension\n"
    end
    
    if $current_platform == "wm"
        $rhoelements_features += "- Windows Mobile/Windows CE platform support\n"
    end
    
    if $application_build_configs['encrypt_database'] && $application_build_configs['encrypt_database'].to_s == '1'
        #$application_build_configs.delete('encrypt_database')
        $rhoelements_features += "- Database encryption\n"
    end

    if $app_config["capabilities"].index("motorola")
        $rhoelements_features += "- Motorola device capabilities\n"
    end

    if $app_config['extensions'].index('webkit-browser')
        $rhoelements_features += "- Motorola WebKit Browser\n"
    end
    
    $invalid_license = false

    if $rhoelements_features.length() > 0
        #check for RhoElements gem and license
        begin
            require "rhoelements"
            
            $rhoelements_features = ""
            
            # check license
            is_ET1 = (($current_platform == "android") and ($app_config["capabilities"].index("motorola")))
            is_win_platform = (($current_platform == "wm") or ($current_platform == "win32") or $is_rho_simulator )

            if (!is_ET1) and (!is_win_platform)
                 # check the license parameter
                 if (!$application_build_configs["motorola_license"]) or (!$application_build_configs["motorola_license_company"])
                    $invalid_license = true
                 end
            end
            
        rescue Exception => e
            if $app_config['extensions'].index('barcode')
                $app_config['extensions'].delete('barcode')
            end
            if $app_config['extensions'].index('nfc')
                $app_config['extensions'].delete('nfc')
            end
            
            if $application_build_configs['encrypt_database'] && $application_build_configs['encrypt_database'].to_s == '1'
                $application_build_configs.delete('encrypt_database')
            end
        end
    end
        
    $app_config['extensions'].uniq!() if $app_config['extensions']
    $app_config['capabilities'].uniq!() if $app_config['capabilities']
    
    if $invalid_license
        $application_build_configs["motorola_license"] = '123' if !$application_build_configs["motorola_license"]
        $application_build_configs["motorola_license_company"] = 'WRONG' if !$application_build_configs["motorola_license_company"]
    end
    
    puts "$app_config['extensions'] : #{$app_config['extensions'].inspect}"
    puts "$app_config['capabilities'] : #{$app_config['capabilities'].inspect}"

    
    if $current_platform == "bb"
      make_application_build_config_java_file()
      update_rhoprofiler_java_file()
    elsif $current_platform == "wp"
    else
      make_application_build_config_header_file
      make_application_build_capabilities_header_file
      update_rhodefs_header_file
    end

    $rhologhostport = $config["log_host_port"]
    $rhologhostport = 52363 unless $rhologhostport
    begin
$rhologhostaddr = Jake.localip()
    rescue Exception => e
        puts "Jake.localip() error : #{e}"
    end

    $obfuscate_js = (($app_config["obfuscate"].nil? || $app_config["obfuscate"]["js"].nil?) ? nil : 1 )
    $obfuscate_css = (($app_config["obfuscate"].nil? || $app_config["obfuscate"]["css"].nil?) ? nil : 1 )
    $obfuscate_exclude = ($app_config["obfuscate"].nil? ? nil : $app_config["obfuscate"]["exclude_dirs"] )
    $obfuscator = 'res/build-tools/yuicompressor-2.4.7.jar'
  end

  task :qt do
    $qtdir = ENV['QTDIR']
    unless (!$qtdir.nil?) and ($qtdir !~/^\s*$/) and File.directory?($qtdir)
      puts "\nPlease, set QTDIR environment variable to Qt root directory path"
      exit 1
    end
    $qmake = File.join($qtdir, 'bin/qmake')
    $macdeployqt = File.join($qtdir, 'bin/macdeployqt')
  end

  task :rhosimulator do
    $rhosimulator_build = true
  end

  out = `javac -version 2>&1`
  puts "\n\nYour java bin folder does not appear to be on your path.\nThis is required to use rhodes.\n\n" unless $? == 0
end

def copy_assets(asset)
  
  dest = File.join($srcdir,'apps/public')
  
  cp_r asset + "/.", dest, :preserve => true, :remove_destination => true
  
end

def clear_linker_settings
  if $config["platform"] == "iphone"
# outfile = ""
# IO.read($startdir + "/platform/iphone/rhorunner.xcodeproj/project.pbxproj").each_line do |line|
# if line =~ /EXTENSIONS_LDFLAGS = /
# outfile << line.gsub(/EXTENSIONS_LDFLAGS = ".*"/, 'EXTENSIONS_LDFLAGS = ""')
# else
# outfile << line
# end
# end
# File.open($startdir + "/platform/iphone/rhorunner.xcodeproj/project.pbxproj","w") {|f| f.write outfile}
# ENV["EXTENSIONS_LDFLAGS"] = ""

    $ldflags = ""
  end

end

def add_linker_library(libraryname)
# if $config["platform"] == "iphone"
# outfile = ""
# IO.read($startdir + "/platform/iphone/rhorunner.xcodeproj/project.pbxproj").each_line do |line|
# if line =~ /EXTENSIONS_LDFLAGS = /
# outfile << line.gsub(/";/, " $(TARGET_TEMP_DIR)/#{libraryname}\";")
# else
# outfile << line
# end
# end
# File.open($startdir + "/platform/iphone/rhorunner.xcodeproj/project.pbxproj","w") {|f| f.write outfile}
# end
      simulator = $sdk =~ /iphonesimulator/

      if ENV["TARGET_TEMP_DIR"] and ENV["TARGET_TEMP_DIR"] != ""
        tmpdir = ENV["TARGET_TEMP_DIR"]
      else
        tmpdir = $startdir + "/platform/iphone/build/rhorunner.build/#{$configuration}-" +
          ( simulator ? "iphonesimulator" : "iphoneos") + "/rhorunner.build"
      end
  $ldflags << "#{tmpdir}/#{libraryname}\n" unless $ldflags.nil?
end

def set_linker_flags
  if $config["platform"] == "iphone"
      simulator = $sdk =~ /iphonesimulator/
      if ENV["TARGET_TEMP_DIR"] and ENV["TARGET_TEMP_DIR"] != ""
        tmpdir = ENV["TARGET_TEMP_DIR"]
      else
        tmpdir = $startdir + "/platform/iphone/build/rhorunner.build/#{$configuration}-" +
          ( simulator ? "iphonesimulator" : "iphoneos") + "/rhorunner.build"
      end
      mkdir_p tmpdir unless File.exist? tmpdir
      File.open(tmpdir + "/rhodeslibs.txt","w") { |f| f.write $ldflags }
# ENV["EXTENSIONS_LDFLAGS"] = $ldflags
# puts `export $EXTENSIONS_LDFLAGS`
  end

end

def add_extension(path,dest)
  puts 'add_extension - ' + path.to_s + " - " + dest.to_s
  
  start = pwd
  chdir path if File.directory?(path)

  Dir.glob("*").each { |f| cp_r f,dest unless f =~ /^ext(\/|(\.yml)?$)/ }

  chdir start
end

def init_extensions(startdir, dest)
  extentries = []
  nativelib = []
  extlibs = []
  extpaths = $app_config["extpaths"]
    
  puts 'init extensions'
  $app_config["extensions"].each do |extname|
    puts 'ext - ' + extname
    
    extpath = nil
    extpaths.each do |p|
      ep = File.join(p, extname)
      if File.exists? ep
        extpath = ep
        break
      end
    end
    
    puts '1'

    if extpath.nil?
      begin
        $rhodes_extensions = nil
        require extname
        puts '1-2'
        if $rhodes_extensions
            extpath = $rhodes_extensions[0]
            $app_config["extpaths"] << extpath
        end
      rescue Exception => e
        puts "exception"
      end
    end
        
    unless extpath.nil?
      add_extension(extpath, dest) unless dest.nil?

      if $config["platform"] != "bb"
        extyml = File.join(extpath, "ext.yml")
        puts "extyml " + extyml
        
        if File.file? extyml
          extconf = Jake.config(File.open(extyml))
          entry = extconf["entry"]
          nlib = extconf["nativelibs"]
          type = extconf["exttype"]
            
          if nlib != nil
            nlib.each do |libname|
              nativelib << libname
            end
          end
          
          extentries << entry unless entry.nil?
          
          if type.to_s() != "nativelib"
            libs = extconf["libraries"]
            libs = [] unless libs.is_a? Array
            if (!extconf[$config["platform"]].nil?) && (extconf[$config["platform"]]["libraries"].is_a? Array)
              libs = libs + extconf[$config["platform"]]["libraries"]
            end
            if $config["platform"] == "wm" || $config["platform"] == "win32"
              libs.map! { |lib| lib + ".lib" }
            else
              libs.map! { |lib| "lib" + lib + ".a" }
            end
            extlibs += libs
          end
        end
      end
      
    end
    
  end
  
  exts = File.join($startdir, "platform", "shared", "ruby", "ext", "rho", "extensions.c")
  puts "exts " + exts
  
  if $config["platform"] != "bb"
    #exists = []
      
    #if ( File.exists?(exts) )
    # File.new(exts, "r").read.split("\n").each do |line|
    # next if line !~ /^\s*extern\s+void\s+([A-Za-z_][A-Za-z0-9_]*)/
    # exists << $1
    # end
    #end
  
    #if (exists.sort! != extentries.sort! ) || (!File.exists?(exts))
      #File.open(exts, "w") do |f|
      # puts "MODIFY : #{exts}"
        f = StringIO.new("", "w+")
        f.puts "// WARNING! THIS FILE IS GENERATED AUTOMATICALLY! DO NOT EDIT IT MANUALLY!"
        #f.puts "// Generated #{Time.now.to_s}"
        if $config["platform"] == "wm" || $config["platform"] == "win32"
          # Add libraries through pragma
          extlibs.each do |lib|
            f.puts "#pragma comment(lib, \"#{lib}\")"
          end

          nativelib.each do |lib|
            f.puts "#pragma comment(lib, \"#{lib}\")"
          end
        end
          
        extentries.each do |entry|
          f.puts "extern void #{entry}(void);"
        end
    
        f.puts "void Init_Extensions(void) {"
        extentries.each do |entry|
          f.puts " #{entry}();"
        end
        f.puts "}"
      #end
        Jake.modify_file_if_content_changed( exts, f )
    #end

    extlibs.each { |lib| add_linker_library(lib) }
    nativelib.each { |lib| add_linker_library(lib) }

    set_linker_flags
  end
  
  unless $app_config["constants"].nil?
    File.open("rhobuild.rb","w") do |file|
      file << "module RhoBuild\n"
      $app_config["constants"].each do |key,value|
        value.gsub!(/"/,"\\\"")
        file << " #{key.upcase} = \"#{value}\"\n"
      end
      file << "end\n"
    end
  end

  if $excludeextlib and (not dest.nil?)
      chdir dest
      $excludeextlib.each {|e| Dir.glob(e).each {|f| rm f}}
  end
  #puts "end of init extension"
  #exit
end

def public_folder_cp_r(src_dir,dst_dir,level,obfuscate)
  mkdir_p dst_dir if not File.exists? dst_dir
  Dir.foreach(src_dir) do |filename|
    next if filename.eql?('.') || filename.eql?('..')
    filepath = src_dir + '/' + filename
    dst_path = dst_dir + '/' + filename
    if File.directory?(filepath)
      public_folder_cp_r(filepath,dst_path,(level+1),((obfuscate==1) && ((level>0) || $obfuscate_exclude.nil? || !$obfuscate_exclude.include?(filename)) ? 1 : 0))
    else
      if (obfuscate==1) && (((!$obfuscate_js.nil?) && File.extname(filename).eql?(".js")) || ((!$obfuscate_css.nil?) && File.extname(filename).eql?(".css")))
        puts Jake.run('java',['-jar', $obfuscator, filepath, '-o', dst_path])
        unless $? == 0
          puts "Obfuscation error"
          exit 1
        end
      else
        cp filepath, dst_path, :preserve => true
      end
    end
  end
end

def copy_rhoconfig(source, target)
  override = get_config_override_params
  mentioned = Set.new

  lines = []

  # read file and edit overriden parameters
  File.open(source, 'r') do |file|
    while line = file.gets
      match = line.match(/^(\s*)(\w+)(\s*=\s*)/)
      if match
        name = match[2]
        if override.has_key?(name)
          lines << "#{match[1]}#{name}#{match[3]}#{override[name]}"
          mentioned << name
          next
        end
      end
      lines << line
    end
  end

  # append rest of overriden parameters to text
  override.each do |key, value|
    if !mentioned.include?(key)
      lines << ''
      lines << "#{key} = #{value}"
    end
  end

  # write text to target file
  File.open(target, 'w') do |file|
    lines.each { |l| file.puts l }
  end
end

def common_bundle_start(startdir, dest)
  puts "common_bundle_start"
  
  app = $app_path
  rhodeslib = "lib/framework"

  rm_rf $srcdir
  mkdir_p $srcdir
  mkdir_p dest if not File.exists? dest
  mkdir_p File.join($srcdir,'apps')

  start = pwd
  chdir rhodeslib

  Dir.glob("*").each { |f| cp_r f,dest, :preserve => true }

  chdir dest
  Dir.glob("**/rhodes-framework.rb").each {|f| rm f}
  Dir.glob("**/erb.rb").each {|f| rm f}
  Dir.glob("**/find.rb").each {|f| rm f}
  $excludelib.each {|e| Dir.glob(e).each {|f| rm f}}

  chdir start
  clear_linker_settings

  init_extensions(startdir, dest)

  chdir startdir
  #throw "ME"
  cp_r app + '/app',File.join($srcdir,'apps'), :preserve => true
  if File.exists? app + '/public'
    if $obfuscate_js.nil? && $obfuscate_css.nil?
      cp_r app + '/public', File.join($srcdir,'apps'), :preserve => true
    else
      public_folder_cp_r app + '/public', File.join($srcdir,'apps/public'), 0, 1
    end
  end
  copy_rhoconfig(File.join(app, 'rhoconfig.txt'), File.join($srcdir, 'apps', 'rhoconfig.txt'))

  if $app_config["app_type"] == 'rhoelements'
    $config_xml = nil
    if $app_config[$config["platform"]] && $app_config[$config["platform"]]["rhoelements"] && $app_config[$config["platform"]]["rhoelements"]["config"] && (File.exists? File.join(app, $app_config[$config["platform"]]["rhoelements"]["config"]))
      $config_xml = File.join(app, $app_config[$config["platform"]]["rhoelements"]["config"])
    elsif $app_config["rhoelements"] && $app_config["rhoelements"]["config"] && (File.exists? File.join(app, $app_config["rhoelements"]["config"]))
      $config_xml = File.join(app, $app_config["rhoelements"]["config"])
    end
    if $current_platform == "wm"
      if !($config_xml.nil?)
        cp $config_xml, File.join($srcdir,'apps/Config.xml'), :preserve => true
      end
    end
  end

  app_version = "\r\napp_version='#{$app_config["version"]}'"
  app_version += "\r\ntitle_text='#{$app_config["name"]}'" if $current_platform == "win32"
  
  File.open(File.join($srcdir,'apps/rhoconfig.txt'), "a"){ |f| f.write(app_version) }
  File.open(File.join($srcdir,'apps/rhoconfig.txt.timestamp'), "w"){ |f| f.write(Time.now.to_f().to_s()) }
  
  unless $debug
    rm_rf $srcdir + "/apps/app/test"
    rm_rf $srcdir + "/apps/app/SpecRunner"
    rm_rf $srcdir + "/apps/app/mspec"
    rm_rf $srcdir + "/apps/app/mspec.rb"
    rm_rf $srcdir + "/apps/app/spec_runner.rb"
  end


  copy_assets($assetfolder) if ($assetfolder and File.exists? $assetfolder)

  replace_platform = $config['platform']
  replace_platform = "bb6" if $bb6
  replace_platform = "wm" if replace_platform == 'win32'

  [File.join($srcdir,'apps'), ($current_platform == "bb" ? File.join($srcdir,'res') : File.join($srcdir,'lib/res'))].each do |folder|
      chdir folder
      
      Dir.glob("**/*.#{replace_platform}.*").each do |file|
        oldfile = file.gsub(Regexp.new(Regexp.escape('.') + replace_platform + Regexp.escape('.')),'.')
        rm oldfile if File.exists? oldfile
        mv file,oldfile
      end
      
      Dir.glob("**/*.wm.*").each { |f| rm f }
Dir.glob("**/*.wp7.*").each { |f| rm f }
      Dir.glob("**/*.iphone.*").each { |f| rm f }
      Dir.glob("**/*.bb.*").each { |f| rm f }
      Dir.glob("**/*.bb6.*").each { |f| rm f }
      Dir.glob("**/*.android.*").each { |f| rm f }
      Dir.glob("**/.svn").each { |f| rm_rf f }
      Dir.glob("**/CVS").each { |f| rm_rf f }
  end
end

def create_manifest
    require File.dirname(__FILE__) + '/lib/framework/rhoappmanifest'
    
    fappManifest = Rho::AppManifest.enumerate_models(File.join($srcdir, 'apps/app'))
    content = fappManifest.read();
    
    File.open( File.join($srcdir,'apps/app_manifest.txt'), "w"){|file| file.write(content)}
end

def process_exclude_folders
  excl = []

  exclude_platform = $config['platform']
  exclude_platform = "bb6" if $bb6
  exclude_platform = "wm" if exclude_platform == 'win32'

  if $app_config["excludedirs"]
      excl += $app_config["excludedirs"]['all'] if $app_config["excludedirs"]['all']
      excl += $app_config["excludedirs"][exclude_platform] if $app_config["excludedirs"][exclude_platform]
  end
      
  if $config["excludedirs"]
      excl += $config["excludedirs"]['all'] if $config["excludedirs"]['all']
      excl += $config["excludedirs"][exclude_platform] if $config["excludedirs"][exclude_platform]
  end
  
  if excl.size() > 0
      chdir File.join($srcdir)#, 'apps')
  
      excl.each do |mask|
        Dir.glob(mask).each {|f| puts "f: #{f}"; rm_rf f}
      end
      
      chdir File.join($srcdir, 'apps')
  
      excl.each do |mask|
        Dir.glob(mask).each {|f| puts "f: #{f}"; rm_rf f}
      end
      
  end

end

def get_config_override_params
    override = {}
    ENV.each do |key, value|
        key.match(/^rho_override_(.+)$/) do |match|
            override[match[1]] = value
        end
    end
    return override
end

def get_extensions
    value = ENV['rho_extensions']
    return value.split(',') if value
    return []
end

namespace "build" do
  namespace "bundle" do
    task :xruby do
      #needs $config, $srcdir, $excludelib, $bindir
      app = $app_path
   jpath = $config["env"]["paths"]["java"]
      startdir = pwd
      dest = $srcdir
      xruby = File.dirname(__FILE__) + '/res/build-tools/xruby-0.3.3.jar'
      compileERB = "lib/build/compileERB/bb.rb"
      rhodeslib = File.dirname(__FILE__) + "/lib/framework"
      
      common_bundle_start(startdir,dest)

      process_exclude_folders()
      cp_r File.join(startdir, "platform/shared/db/res/db"), File.join($srcdir, 'apps')
      
      chdir startdir
      
      #create manifest
      create_manifest
      
      #"compile ERB"
      #ext = ".erb"
      #Find.find($srcdir) do |path|
      # if File.extname(path) == ext
      # rbText = ERB.new( IO.read(path) ).src
      # newName = File.basename(path).sub('.erb','_erb.rb')
      # fName = File.join(File.dirname(path), newName)
      # frb = File.new(fName, "w")
      # frb.write( rbText )
      # frb.close()
      # end
      #end
      cp compileERB, $srcdir
      puts "Running bb.rb"

      puts `#{$rubypath} -I"#{rhodeslib}" "#{$srcdir}/bb.rb"`
      unless $? == 0
        puts "Error interpreting erb code"
        exit 1
      end

      rm "#{$srcdir}/bb.rb"

      chdir $bindir
      # -n#{$bundleClassName}
      output = `java -jar "#{xruby}" -v -c RhoBundle 2>&1`
      output.each_line { |x| puts ">>> " + x }
      unless $? == 0
        puts "Error interpreting ruby code"
        exit 1
      end
      chdir startdir
      chdir $srcdir
  
      Dir.glob("**/*.rb") { |f| rm f }
      Dir.glob("**/*.erb") { |f| rm f }
=begin
# RubyIDContainer.* files takes half space of jar why we need it?
Jake.unjar("../RhoBundle.jar", $tmpdir)
Dir.glob($tmpdir + "/**/RubyIDContainer.class") { |f| rm f }
rm "#{$bindir}/RhoBundle.jar"
chdir $tmpdir
puts `jar cf #{$bindir}/RhoBundle.jar #{$all_files_mask}`
rm_rf $tmpdir
mkdir_p $tmpdir
chdir $srcdir
=end

      puts `"#{File.join(jpath,'jar')}" uf ../RhoBundle.jar apps/#{$all_files_mask}`
      unless $? == 0
        puts "Error creating Rhobundle.jar"
        exit 1
      end
      chdir startdir
      
    end

    # its task for compiling ruby code in rhostudio
    # TODO: temporary fix I hope. This code is copied from line 207 of this file
    task :rhostudio => ["config:wm"] do

      if RUBY_PLATFORM =~ /(win|w)32$/
        $all_files_mask = "*.*"
        $rubypath = "res/build-tools/RhoRuby.exe"
      else
        $all_files_mask = "*"
        if RUBY_PLATFORM =~ /darwin/
          $rubypath = "res/build-tools/RubyMac"
        else
          $rubypath = "res/build-tools/rubylinux"
        end
      end

      Rake::Task["build:bundle:noxruby"].invoke

      Jake.build_file_map( File.join($srcdir, "apps"), "rhofilelist.txt" )
    end
    
    task :noxruby do
      app = $app_path
      rhodeslib = File.dirname(__FILE__) + "/lib/framework"
      compileERB = "lib/build/compileERB/default.rb"
      compileRB = "lib/build/compileRB/compileRB.rb"
      startdir = pwd
      dest = $srcdir + "/lib"

      common_bundle_start(startdir,dest)
      process_exclude_folders
      chdir startdir
      
      create_manifest
      
      cp compileERB, $srcdir
      puts "Running default.rb"

      puts `#{$rubypath} -I"#{rhodeslib}" "#{$srcdir}/default.rb"`
      unless $? == 0
        puts "Error interpreting erb code"
        exit 1
      end

      rm "#{$srcdir}/default.rb"

      cp compileRB, $srcdir
      puts "Running compileRB"
      puts `#{$rubypath} -I"#{rhodeslib}" "#{$srcdir}/compileRB.rb"`
      unless $? == 0
        puts "Error interpreting ruby code"
        exit 1
      end

      chdir $srcdir
      Dir.glob("**/*.rb") { |f| rm f }
      Dir.glob("**/*.erb") { |f| rm f }
  
      chdir startdir

      cp_r "platform/shared/db/res/db", $srcdir
    end
    
    task :upgrade_package do
    
      $bindir = File.join($app_path, "bin")
      $current_platform = 'empty'
      $srcdir = File.join($bindir, "RhoBundle")
    
      $targetdir = File.join($bindir, "target")
      $excludelib = ['**/builtinME.rb','**/ServeME.rb','**/dateME.rb','**/rationalME.rb']
      $tmpdir = File.join($bindir, "tmp")
      $appname = $app_config["name"]
      $appname = "Rhodes" if $appname.nil?
      $vendor = $app_config["vendor"]
      $vendor = "rhomobile" if $vendor.nil?
      $vendor = $vendor.gsub(/^[^A-Za-z]/, '_').gsub(/[^A-Za-z0-9]/, '_').gsub(/_+/, '_').downcase
      $appincdir = File.join $tmpdir, "include"

      Rake::Task["config:common"].invoke

      Rake::Task["build:bundle:noxruby"].invoke
      
      new_zip_file = File.join($srcdir, "apps", "upgrade_bundle.zip")
      
      if RUBY_PLATFORM =~ /(win|w)32$/
        begin
      
          require 'rubygems'
          require 'zip/zip'
          require 'find'
          require 'fileutils'
          include FileUtils

          root = $srcdir
          
          new_zip_file = File.join($srcdir, "upgrade_bundle.zip")

          Zip::ZipFile.open(new_zip_file, Zip::ZipFile::CREATE)do |zipfile|
            Find.find(root) do |path|
                  Find.prune if File.basename(path)[0] == ?.
                  dest = /apps\/(\w.*)/.match(path)
                  if dest
                      puts ' add file to zip : '+dest[1].to_s
                      zipfile.add(dest[1],path)
                  end
            end
          end
        rescue Exception => e
          puts 'ERROR !'
          puts 'Require "rubyzip" gem for make zip file !'
          puts 'Install gem by "gem install rubyzip"'
        end
      else
        chdir File.join($srcdir, "apps")
        sh %{zip -r upgrade_bundle.zip .}
      end

      cp new_zip_file, $bindir
      
      rm new_zip_file
      
    end
    

    task :noiseq do
      app = $app_path
      rhodeslib = File.dirname(__FILE__) + "/lib/framework"
compileERB = "lib/build/compileERB/bb.rb"
      startdir = pwd
      dest = $srcdir + "/lib"

      common_bundle_start(startdir,dest)
      process_exclude_folders
      chdir startdir
      
      create_manifest
  
cp compileERB, $srcdir
      puts "Running bb.rb"

      puts `#{$rubypath} -I#{rhodeslib} "#{$srcdir}/bb.rb"`
      unless $? == 0
        puts "Error interpreting erb code"
        exit 1
      end

      rm "#{$srcdir}/bb.rb"

      chdir $srcdir
      Dir.glob("**/*.erb") { |f| rm f }

chdir startdir
      cp_r "platform/shared/db/res/db", $srcdir
    end
  end
end


# Simple rakefile that loads subdirectory 'rhodes' Rakefile
# run "rake -T" to see list of available tasks

#desc "Get versions"
task :get_version do

  #genver = "unknown"
  iphonever = "unknown"
  #symver = "unknown"
  wmver = "unknown"
  androidver = "unknown"
  

  # File.open("res/generators/templates/application/build.yml","r") do |f|
  # file = f.read
  # if file.match(/version: (\d+\.\d+\.\d+)/)
  # genver = $1
  # end
  # end

  File.open("platform/iphone/Info.plist","r") do |f|
    file = f.read
    if file.match(/CFBundleVersion<\/key>\s+<string>(\d+\.\d+\.*\d*)<\/string>/)
      iphonever = $1
    end
  end

  # File.open("platform/symbian/build/release.properties","r") do |f|
  # file = f.read
  # major = ""
  # minor = ""
  # build = ""
  #
  # if file.match(/release\.major=(\d+)/)
  # major = $1
  # end
  # if file.match(/release\.minor=(\d+)/)
  # minor = $1
  # end
  # if file.match(/build\.number=(\d+)/)
  # build = $1
  # end
  #
  # symver = major + "." + minor + "." + build
  # end

  File.open("platform/android/Rhodes/AndroidManifest.xml","r") do |f|
    file = f.read
    if file.match(/versionName="(\d+\.\d+\.*\d*)"/)
      androidver = $1
    end
  end

  gemver = "unknown"
  rhodesver = "unknown"
  frameworkver = "unknown"

  File.open("lib/rhodes.rb","r") do |f|
    file = f.read
    if file.match(/VERSION = '(\d+\.\d+\.*\d*)'/)
      gemver = $1
    end
  end

  File.open("lib/framework/rhodes.rb","r") do |f|
    file = f.read
    if file.match(/VERSION = '(\d+\.\d+\.*\d*)'/)
      rhodesver = $1
    end
  end

  File.open("lib/framework/version.rb","r") do |f|
    file = f.read
    if file.match(/VERSION = '(\d+\.\d+\.*\d*)'/)
      frameworkver = $1
    end
  end

  

  puts "Versions:"
  #puts " Generator: " + genver
  puts " iPhone: " + iphonever
  #puts " Symbian: " + symver
  #puts " WinMo: " + wmver
  puts " Android: " + androidver
  puts " Gem: " + gemver
  puts " Rhodes: " + rhodesver
  puts " Framework: " + frameworkver
end

#desc "Set version"
task :set_version, [:version] do |t,args|
  throw "You must pass in version" if args.version.nil?
  ver = args.version.split(/\./)
  major = ver[0]
  minor = ver[1]
  build = ver[2]
  
  throw "Invalid version format. Must be in the format of: major.minor.build" if major.nil? or minor.nil? or build.nil?

  verstring = major+"."+minor+"."+build
  origfile = ""

  # File.open("res/generators/templates/application/build.yml","r") { |f| origfile = f.read }
  # File.open("res/generators/templates/application/build.yml","w") do |f|
  # f.write origfile.gsub(/version: (\d+\.\d+\.\d+)/, "version: #{verstring}")
  # end
  

  File.open("platform/iphone/Info.plist","r") { |f| origfile = f.read }
  File.open("platform/iphone/Info.plist","w") do |f|
    f.write origfile.gsub(/CFBundleVersion<\/key>(\s+)<string>(\d+\.\d+\.*\d*)<\/string>/, "CFBundleVersion</key>\n\t<string>#{verstring}</string>")
  end

  # File.open("platform/symbian/build/release.properties","r") { |f| origfile = f.read }
  # File.open("platform/symbian/build/release.properties","w") do |f|
  # origfile.gsub!(/release\.major=(\d+)/,"release.major=#{major}")
  # origfile.gsub!(/release\.minor=(\d+)/,"release.minor=#{minor}")
  # origfile.gsub!(/build\.number=(\d+)/,"build.number=#{build}")
  # f.write origfile
  # end

  File.open("platform/android/Rhodes/AndroidManifest.xml","r") { |f| origfile = f.read }
  File.open("platform/android/Rhodes/AndroidManifest.xml","w") do |f|
    origfile.match(/versionCode="(\d+)"/)
    vercode = $1.to_i + 1
    origfile.gsub!(/versionCode="(\d+)"/,"versionCode=\"#{vercode}\"")
    origfile.gsub!(/versionName="(\d+\.\d+\.*\d*)"/,"versionName=\"#{verstring}\"")

    f.write origfile
  end
  ["lib/rhodes.rb","lib/framework/rhodes.rb","lib/framework/version.rb"].each do |versionfile|
  
    File.open(versionfile,"r") { |f| origfile = f.read }
    File.open(versionfile,"w") do |f|
      origfile.gsub!(/^(\s*VERSION) = '(\d+\.\d+\.*\d*)'/, '\1 = \''+ verstring + "'")
      f.write origfile
    end
  end

  Rake::Task[:get_version].invoke
end



namespace "buildall" do
  namespace "bb" do
    # desc "Build all jdk versions for blackberry"
    task :production => "config:common" do
      $config["env"]["paths"].each do |k,v|
        if k.to_s =~ /^4/
          puts "BUILDING VERSION: #{k}"
          $app_config["bbver"] = k
# Jake.reconfig($config)
 
          #reset all tasks used for building
          Rake::Task["config:bb"].reenable
          Rake::Task["build:bb:rhobundle"].reenable
          Rake::Task["build:bb:rhodes"].reenable
          Rake::Task["build:bb:rubyvm"].reenable
          Rake::Task["device:bb:dev"].reenable
          Rake::Task["device:bb:production"].reenable
          Rake::Task["device:bb:rhobundle"].reenable
          Rake::Task["package:bb:dev"].reenable
          Rake::Task["package:bb:production"].reenable
          Rake::Task["package:bb:rhobundle"].reenable
          Rake::Task["package:bb:rhodes"].reenable
          Rake::Task["package:bb:rubyvm"].reenable
          Rake::Task["device:bb:production"].reenable
          Rake::Task["clean:bb:preverified"].reenable

          Rake::Task["clean:bb:preverified"].invoke
          Rake::Task["device:bb:production"].invoke
        end
      end

    end
  end
end


task :gem do
  puts "Removing old gem"
  rm_rf Dir.glob("rhodes*.gem")
  puts "Copying Rakefile"
  cp "Rakefile", "rakefile.rb"
  
  puts "Building manifest"
  out = ""
  Dir.glob("**/*") do |fname|
    # TODO: create exclusion list
    out << fname + "\n" if File.file? fname and not fname =~ /rhoconnect-client/
  end
  File.open("Manifest.txt",'w') {|f| f.write(out)}

  puts "Loading gemspec"
  require 'rubygems'
  spec = Gem::Specification.load('rhodes.gemspec')

  puts "Building gem"
  gemfile = Gem::Builder.new(spec).build
end

namespace "rhomobile-debug" do
    task :gem do
      puts "Removing old gem"
      rm_rf Dir.glob("rhomobile-debug*.gem")
      rm_rf "rhomobile-debug"
      
      mkdir_p "rhomobile-debug"
      mkdir_p "rhomobile-debug/lib"
      cp 'lib/extensions/debugger/debugger.rb', "rhomobile-debug/lib", :preserve => true
      cp 'lib/extensions/debugger/README.md', "rhomobile-debug", :preserve => true
      cp 'lib/extensions/debugger/LICENSE', "rhomobile-debug", :preserve => true
      cp 'lib/extensions/debugger/CHANGELOG', "rhomobile-debug", :preserve => true
      
      cp 'rhomobile-debug.gemspec', "rhomobile-debug", :preserve => true
      
      startdir = pwd
      chdir 'rhomobile-debug'
      
      puts "Loading gemspec"
      require 'rubygems'
      spec = Gem::Specification.load('rhomobile-debug.gemspec')

      puts "Building gem"
      gemfile = Gem::Builder.new(spec).build
      
      Dir.glob("rhomobile-debug*.gem").each do |f|
        cp f, startdir, :preserve => true
      end

      chdir startdir
      rm_rf "rhomobile-debug"
    end
end

task :tasks do
  Rake::Task.tasks.each {|t| puts t.to_s.ljust(27) + "# " + t.comment.to_s}
end

task :switch_app => "config:common" do
  rhobuildyml = File.dirname(__FILE__) + "/rhobuild.yml"
  if File.exists? rhobuildyml
    config = YAML::load_file(rhobuildyml)
  else
    puts "Cant find rhobuild.yml"
    exit 1
  end
  config["env"]["app"] = $app_path.gsub(/\\/,"/")
  File.open( rhobuildyml, 'w' ) do |out|
    YAML.dump( config, out )
  end
end


#Rake::RDocTask.new do |rd|
#RDoc::Task.new do |rd|
# rd.main = "README.textile"
# rd.rdoc_files.include("README.textile", "lib/framework/**/*.rb")
#end
#Rake::Task["rdoc"].comment=nil
#Rake::Task["rerdoc"].comment=nil

#task :rdocpush => :rdoc do
# puts "Pushing RDOC. This may take a while"
# `scp -r html/* dev@dev.rhomobile.com:dev.rhomobile.com/rhodes/`
#end

namespace "build" do
    # desc "Build rhoconnect-client package"
    task :rhoconnect_client do

        ver = File.read("rhoconnect-client/version").chomp #.gsub(".", "_")
        zip_name = "rhoconnect-client-"+ver+".zip"

        bin_dir = "rhoconnect-client-bin"
        src_dir = bin_dir + "/rhoconnect-client-"+ver #"/src"
        shared_dir = src_dir + "/platform/shared"
        rm_rf bin_dir
        rm zip_name if File.exists? zip_name
        mkdir_p bin_dir
        mkdir_p src_dir

        cp_r 'rhoconnect-client', src_dir, :preserve => true
        
        mv src_dir+"/rhoconnect-client/license", src_dir
        mv src_dir+"/rhoconnect-client/README.textile", src_dir
        mv src_dir+"/rhoconnect-client/version", src_dir
        mv src_dir+"/rhoconnect-client/changelog", src_dir
                
        Dir.glob(src_dir+"/rhoconnect-client/**/*").each do |f|
#puts f

            rm_rf f if f.index("/build/") || f.index(".DS_Store")
 
        end

        mkdir_p shared_dir
        
        Dir.glob("platform/shared/*").each do |f|
            next if f == "platform/shared/ruby" || f == "platform/shared/rubyext" || f == "platform/shared/xruby" || f == "platform/shared/shttpd" ||
                f == "platform/shared/stlport" || f == "platform/shared/qt"
            #puts f
            cp_r f, shared_dir #, :preserve => true
        end
        startdir = pwd
        chdir bin_dir
        puts `zip -r #{File.join(startdir, zip_name)} *`
                
        chdir startdir
        
        rm_rf bin_dir
    end
end

namespace "run" do

    task :set_rhosimulator_flag do
        $is_rho_simulator = true
    end

    task :rhosimulator_base => [:set_rhosimulator_flag, "config:common"] do
        puts "rho_reload_app_changes : #{ENV['rho_reload_app_changes']}"
        $path = ""
        $args = ["-approot='#{$app_path}'", "-rhodespath='#{$startdir}'"]
        $args << "-security_token=#{ENV['security_token']}" if !ENV['security_token'].nil?
        cmd = nil

        if RUBY_PLATFORM =~ /(win|w)32$/
            if $config['env']['paths']['rhosimulator'] and $config['env']['paths']['rhosimulator'].length() > 0
                $path = File.join( $config['env']['paths']['rhosimulator'], "rhosimulator.exe" )
            else
                $path = File.join( $startdir, "platform/win32/RhoSimulator/rhosimulator.exe" )
            end
        elsif RUBY_PLATFORM =~ /darwin/
            if $config['env']['paths']['rhosimulator'] and $config['env']['paths']['rhosimulator'].length() > 0
                $path = File.join( $config['env']['paths']['rhosimulator'], "RhoSimulator.app" )
            else
                $path = File.join( $startdir, "platform/osx/bin/RhoSimulator/RhoSimulator.app" )
            end
            cmd = 'open'
            $args.unshift($path, '--args')
        else
            if $config['env']['paths']['rhosimulator'] and $config['env']['paths']['rhosimulator'].length() > 0
                # $path = File.join( $config['env']['paths']['rhosimulator'], "RhoSimulator" )
            else
                # $path = File.join( $startdir, "platform/linux/bin/RhoSimulator/RhoSimulator" )
            end
            $args << ">/dev/null"
            $args << "2>/dev/null"
        end

        $appname = $app_config["name"].nil? ? "Rhodes" : $app_config["name"]
        if !File.exists?($path)
            puts "Cannot find RhoSimulator: '#{$path}' does not exists"
            puts "Check sdk path in build.yml - it should point to latest rhodes (run 'set-rhodes-sdk' in application folder) OR"

            if $config['env']['paths']['rhosimulator'] and $config['env']['paths']['rhosimulator'].length() > 0
                puts "Check 'env:paths:rhosimulator' path in '<rhodes>/rhobuild.yml' OR"
            end
            
            puts "Install Rhodes gem OR"
            puts "Install RhoSimulator and modify 'env:paths:rhosimulator' section in '<rhodes>/rhobuild.yml'"
            exit 1
        end

        sim_conf = "rhodes_path='#{$startdir}'\r\n"
        sim_conf += "app_version='#{$app_config["version"]}'\r\n"
        sim_conf += "app_name='#{$appname}'\r\n"
        if ( ENV['rho_reload_app_changes'] )
            sim_conf += "reload_app_changes=#{ENV['rho_reload_app_changes']}\r\n"
        else
            sim_conf += "reload_app_changes=1\r\n"
        end

        if $config['debug']
            sim_conf += "debug_port=#{$config['debug']['port']}\r\n"
        else
            sim_conf += "debug_port=\r\n"
        end
        
        if $config['debug'] && $config['debug']['host'] && $config['debug']['host'].length() > 0
            sim_conf += "debug_host='#{$config['debug']['host']}'\r\n"
        else
            sim_conf += "debug_host='127.0.0.1'\r\n"
        end
        
        sim_conf += $rhosim_config if $rhosim_config

        #check gem extensions
        config_ext_paths = ""
        extpaths = $app_config["extpaths"]
        $app_config["extensions"].each do |extname|
        
            extpath = nil
            extpaths.each do |p|
              ep = File.join(p, extname)
              if File.exists? ep
                extpath = ep
                break
              end
            end

            if extpath.nil?
                begin
                    $rhodes_extensions = nil
                    require extname
                    extpath = $rhodes_extensions[0] unless $rhodes_extensions.nil?
                    config_ext_paths += "#{extpath};" if extpath && extpath.length() > 0
                rescue Exception => e
                end
            else
            
                # if $config["platform"] != "bb"
                # extyml = File.join(extpath, "ext.yml")
                # next if File.file? extyml
                # end
                
                config_ext_paths += "#{extpath};" if extpath && extpath.length() > 0
            end
        end

        sim_conf += "ext_path=#{config_ext_paths}\r\n" if config_ext_paths && config_ext_paths.length() > 0

        security_token = $app_config["security_token"]
        sim_conf += "security_token=#{security_token}\r\n" if !security_token.nil?
        
        fdir = File.join($app_path, 'rhosimulator')
        mkdir fdir unless File.exist?(fdir)
            
        get_config_override_params.each do |key, value|
            if key != 'start_path'
                puts "Override '#{key}' is not supported."
                next
            end
            sim_conf += "#{key}=#{value}\r\n"
        end

        fname = File.join(fdir, 'rhosimconfig.txt')
        File.open(fname, "wb") do |fconf|
            fconf.write( sim_conf )
        end

        if not cmd.nil?
            $path = cmd
        end
    end

    #desc "Run application on RhoSimulator"
    task :rhosimulator => "run:rhosimulator_base" do
        puts 'start rhosimulator'
        Jake.run2 $path, $args, {:nowait => true}
    end

    task :rhosimulator_debug => "run:rhosimulator_base" do
        puts 'start rhosimulator debug'
        Jake.run2 $path, $args, {:nowait => true}

        if RUBY_PLATFORM =~ /darwin/
while 1
          end
        end
    end

end

namespace "build" do
    task :rhosimulator do
        if RUBY_PLATFORM =~ /(win|w)32$/
            Rake::Task["build:win32:rhosimulator"].invoke
        elsif RUBY_PLATFORM =~ /darwin/
            Rake::Task["build:osx:rhosimulator"].invoke
        else
            puts "Sorry, at this time RhoSimulator can be built for Windows and Mac OS X only"
            exit 1
        end
    end

    task :rhosimulator_version do
        $rhodes_version = File.read(File.join($startdir,'version')).chomp
        File.open(File.join($startdir, 'platform/shared/qt/rhodes/RhoSimulatorVersion.h'), "wb") do |fversion|
            fversion.write( "#define RHOSIMULATOR_VERSION \"#{$rhodes_version}\"\n" )
        end
    end
end


at_exit do
  if $app_config && !$app_config["sdk"].nil?
    puts '********* NOTE: You use sdk parameter in build.yml !****************'
    puts 'To use latest Rhodes gem, run migrate-rhodes-app in application folder or comment sdk in build.yml.'
    puts '************************************************************************'
  end
  
  if (!$rhoelements_features.nil?) && ($rhoelements_features.length() > 0)
    puts '********* WARNING ************************************************************************'
    puts ' The following features are only available in RhoElements v2 and above:'
    puts $rhoelements_features
    puts ' For more information go to http://www.motorolasolutions.com/rhoelements '
    puts '**************************************************************************************'
  end
  
  if $invalid_license
    puts '********* WARNING ************************************************************************'
    puts ' License is required to run RhoElements application.'
    puts ' Please, provide "motorola_license" and "motorola_license_company" parameters in build.yml.'
    puts ' For more information go to http://www.motorolasolutions.com/rhoelements '
    puts '**************************************************************************************'
  end
  
end
Something went wrong with that request. Please try again.