iOS 调用私有函数安装app 卸载 app

1、环境

  1、OS X EI Caption 10.11.1 & Xcode 7

  2、Xcode安装Command Line Tools 

  3、iPhone 安装AppSync

 

2、MobileInstallation.framework 私有API

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*!
 *  @brief  Mobile Installation 的回调定义
 */
 
typedef void (*MobileInstallationCallback)(CFDictionaryRef information);
 
/*!
 *  @brief  Mobile Installation 安装App (8.0)
 *  @param  bundlePath          IPA文件路径
 *  @param  parameters          unknown
 *  @param  unknown1            unknown
 *  @param  unknown2            unknown
 */
 
extern int MobileInstallationInstallForLaunchServices(CFStringRef bundlePath, CFDictionaryRef parameters, void *unknown1, void *unknown2) NS_AVAILABLE_IOS(8_0);
/*!
 *  @brief  Mobile Installation 卸载App (8.0)
 *  @param  bundleIdentifier    App的Bundle ID
 *  @param  parameters          unknown
 *  @param  callback            Mobile Installation 的回调
 *  @param  unknown             unknown
 */
 
extern int MobileInstallationUninstallForLaunchServices(CFStringRef bundleIdentifier, CFDictionaryRef parameters, MobileInstallationCallback callback, void *unknown) NS_AVAILABLE_IOS(8_0);

  以上是函数符号

 

3、关键代码

  

复制代码
    void *lib = dlopen([frameworkPath UTF8String], RTLD_LAZY);
    if (lib)
    {
        MobileInstallationInstall pMobileInstallationInstall = (MobileInstallationInstall)dlsym(lib, "MobileInstallationInstall");
        if (pMobileInstallationInstall)
        {
            NSString* temp = [NSTemporaryDirectory() stringByAppendingPathComponent:[@"Temp_" stringByAppendingString:ipaPath.lastPathComponent]];
            if (![[NSFileManager defaultManager] copyItemAtPath:ipaPath toPath:temp error:nil]) {
                [self showAlertMessage:@"检查要安装的IPA路径是否正确!" Title:@"复制IPA文件失败"];
                [SVProgressHUD dismiss];
                return NO;
            }
            int ret = pMobileInstallationInstall(temp, [NSDictionary dictionaryWithObject:@"User" forKey:@"ApplicationType"], 0, temp);
            [[NSFileManager defaultManager] removeItemAtPath:temp error:nil];
            if (ret == 0)   {
                [self showAlertMessage:@"请退出桌面确定是否有个HelloIPA的程序!" Title:@"安装成功"];
                [SVProgressHUD dismiss];
                return YES;
            }
            else {
                [self showAlertMessage:@"若为真机,确定该设备已经jailbreak!" Title:@"安装失败"];
                [SVProgressHUD dismiss];
                return NO;
            }
        }
    }
    else {
        [self showAlertMessage:@"检查MobileInstallation.framework路径是否正确!" Title:@"无法连接到MobileInstallation"];
        [SVProgressHUD dismiss];
        return NO;
    }
    return NO;
复制代码

 

  以上代码可以在App中使用

 

4、使用ldid签名

  上面的函数如果没有经过签名,会返回-1

  

<dict><key>application-identifier</key><string>com.q2q.testIPAInstall222</string><key>com.apple.private.mobileinstall.allowedSPI</key><array><string>Install</string><string>Browse</string><string>Uninstall</string><string>InstallForLaunchServices</string><string>UninstallForLaunchServices</string></array><key>com.apple.springboard.debugapplications</key><true/><key>get-task-allow</key><true/><key>task_for_pid-allow</key><true/></dict>

 

  直接使用ldid签名可执行文件后,重新打包成ipa就可以了。

  如果觉得复杂,也可以在Xcode中设置

使用普通的账号就可以了

https://github.com/kryhear/IPAInstaller/tree/master/testIPAInstall.xcodeproj 工程中的代码没有设置签名,导致调用是不成功的

 

5、ipainstaller源码

  

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
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
#include <dlfcn.h>
#import <objc/runtime.h>
#import <UIKit/UIKit.h>
#import "ZipArchive/ZipArchive.h"
#import "UIDevice-Capabilities/UIDevice-Capabilities.h"
 
#define EXECUTABLE_VERSION @"3.4.1"
 
#define KEY_INSTALL_TYPE @"User"
#define KEY_SDKPATH "/System/Library/PrivateFrameworks/MobileInstallation.framework/MobileInstallation"
 
#define IPA_FAILED -1
 
typedef int (*MobileInstallationInstall)(NSString *path, NSDictionary *dict, void *na, NSString *backpath);
typedef int (*MobileInstallationUninstall)(NSString *bundleID, NSDictionary *dict, void *na);
 
@interface LSApplicationWorkspace : NSObject
+ (LSApplicationWorkspace *)defaultWorkspace;
- (BOOL)installApplication:(NSURL *)path withOptions:(NSDictionary *)options;
- (BOOL)uninstallApplication:(NSString *)identifier withOptions:(NSDictionary *)options;
- (BOOL)applicationIsInstalled:(NSString *)appIdentifier;
- (NSArray *)allInstalledApplications;
- (NSArray *)allApplications;
- (NSArray *)applicationsOfType:(unsigned int)appType; // 0 for user, 1 for system
@end
 
@interface LSApplicationProxy : NSObject
+ (LSApplicationProxy *)applicationProxyForIdentifier:(id)appIdentifier;
@property(readonly) NSString * applicationIdentifier;
@property(readonly) NSString * bundleVersion;
@property(readonly) NSString * bundleExecutable;
@property(readonly) NSArray * deviceFamily;
@property(readonly) NSURL * bundleContainerURL;
@property(readonly) NSString * bundleIdentifier;
@property(readonly) NSURL * bundleURL;
@property(readonly) NSURL * containerURL;
@property(readonly) NSURL * dataContainerURL;
@property(readonly) NSString * localizedShortName;
@property(readonly) NSString * localizedName;
@property(readonly) NSString * shortVersionString;
@end
 
static NSString *SystemVersion = nil;
static int DeviceModel = 0;
 
static BOOL isUninstall = NO;
static BOOL isGetInfo = NO;
static BOOL isListing = NO;
static BOOL isBackup = NO;
static BOOL isBackupFull = NO;
 
static BOOL cleanInstall = NO;
static int quietInstall = 0; //0 is show all outputs, 1 is to show only errors, 2 is to show nothing
static BOOL forceInstall = NO;
static BOOL removeMetadata = NO;
static BOOL deleteFile = NO;
static BOOL notRestore = NO;
 
static NSString * randomStringInLength(int len) {
    NSString *ret = @"";
    NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    for (int i=0; i<len; i++)
        ret = [NSString stringWithFormat:@"%@%C", ret, [letters characterAtIndex:arc4random() % [letters length]]];
    return ret;
}
 
static BOOL removeAllContentsUnderPath(NSString *path) {
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    BOOL isDirectory;
    if ([fileMgr fileExistsAtPath:path isDirectory:&isDirectory]) {
        if (isDirectory) {
            NSArray *dirContents = [fileMgr contentsOfDirectoryAtPath:path error:nil];
            BOOL allRemoved = YES;
            for (int unsigned j=0; j<[dirContents count]; j++) {
                if (![fileMgr removeItemAtPath:[path stringByAppendingPathComponent:[dirContents objectAtIndex:j]] error:nil])
                    allRemoved = NO;
            }
            if (!allRemoved)
                return NO;
            if (![fileMgr removeItemAtPath:path error:nil])
                return NO;
        }
    }
    return YES;
}
 
static void setPermissionsForPath(NSString *path) {
    NSFileManager *fileMgr = [NSFileManager defaultManager];
 
    //Set root folder's attributes
    NSDictionary *directoryAttributes = [fileMgr attributesOfItemAtPath:path error:nil];
    NSMutableDictionary *defaultDirectoryAttributes = [NSMutableDictionary dictionaryWithCapacity:[directoryAttributes count]];
    [defaultDirectoryAttributes setDictionary:directoryAttributes];
 
    [defaultDirectoryAttributes setObject:[NSNumber numberWithInt:501] forKey:NSFileOwnerAccountID];
    [defaultDirectoryAttributes setObject:@"mobile" forKey:NSFileOwnerAccountName];
    [defaultDirectoryAttributes setObject:[NSNumber numberWithInt:501] forKey:NSFileGroupOwnerAccountID];
    [defaultDirectoryAttributes setObject:@"mobile" forKey:NSFileGroupOwnerAccountName];
 
    [defaultDirectoryAttributes setObject:[NSNumber numberWithShort:0755] forKey:NSFilePosixPermissions];
 
    [fileMgr setAttributes:defaultDirectoryAttributes ofItemAtPath:path error:nil];
 
    for (NSString *subPath in [fileMgr contentsOfDirectoryAtPath:path error:nil]) {
        NSDictionary *attributes = [fileMgr attributesOfItemAtPath:[path stringByAppendingPathComponent:subPath] error:nil];
        if ([[attributes objectForKey:NSFileType] isEqualToString:NSFileTypeRegular]) {
            NSMutableDictionary *defaultAttributes = [NSMutableDictionary dictionaryWithDictionary:directoryAttributes];
 
            [defaultAttributes setObject:[NSNumber numberWithInt:501] forKey:NSFileOwnerAccountID];
            [defaultAttributes setObject:@"mobile" forKey:NSFileOwnerAccountName];
            [defaultAttributes setObject:[NSNumber numberWithInt:501] forKey:NSFileGroupOwnerAccountID];
            [defaultAttributes setObject:@"mobile" forKey:NSFileGroupOwnerAccountName];
            [defaultAttributes setObject:[NSNumber numberWithShort:0644] forKey:NSFilePosixPermissions];
 
            [fileMgr setAttributes:defaultAttributes ofItemAtPath:[path stringByAppendingPathComponent:subPath] error:nil];
        } else if ([[attributes objectForKey:NSFileType] isEqualToString:NSFileTypeDirectory])
            setPermissionsForPath([path stringByAppendingPathComponent:subPath]);
        else {
            //Ignore symblic links
        }
    }
}
 
static void setExecutables(NSString *dirPath) {
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    BOOL isDir;
    if (![fileMgr fileExistsAtPath:dirPath isDirectory:&isDir])
        return;
    if (!isDir)
        return;
     
    NSString *infoPlistPath = [dirPath stringByAppendingPathComponent:@"Info.plist"];
    if ([fileMgr fileExistsAtPath:infoPlistPath]) {
        NSDictionary *infoDict = [NSDictionary dictionaryWithContentsOfFile:infoPlistPath];
        NSString *exeName = [infoDict objectForKey:@"CFBundleExecutable"];
        NSString *exePath = [dirPath stringByAppendingPathComponent:exeName];
        if ([fileMgr fileExistsAtPath:exePath]) {
            NSDictionary *attributes = [fileMgr attributesOfItemAtPath:exePath error:nil];
            if ([[attributes objectForKey:NSFileType] isEqualToString:NSFileTypeRegular]) {
                NSMutableDictionary *executableAttributes = [NSMutableDictionary dictionaryWithDictionary:attributes];
                [executableAttributes setObject:[NSNumber numberWithShort:0755] forKey:NSFilePosixPermissions];
                [fileMgr setAttributes:executableAttributes ofItemAtPath:exePath error:nil];
            }
        }
    }
     
    for (NSString *subPath in [fileMgr contentsOfDirectoryAtPath:dirPath error:nil]) {
        NSString *subDirPath = [dirPath stringByAppendingPathComponent:subPath];
        NSDictionary *attributes = [fileMgr attributesOfItemAtPath:subDirPath error:nil];
        if ([[attributes objectForKey:NSFileType] isEqualToString:NSFileTypeDirectory])
            setExecutables(subDirPath);
    }
}
 
static int versionCompare(NSString *ver1, NSString *ver2) {
    //-1: ver1<ver2; 0: ver1=ver2; 1: ver1>ver2
    BOOL isEmpty1 = (ver1 == nil || [ver1 length] == 0);
    BOOL isEmpty2 = (ver2 == nil || [ver2 length] == 0);
    if (isEmpty1 && isEmpty2)
        return 0;
    else if (isEmpty1 && !isEmpty2)
        return -1;
    else if (!isEmpty1 && isEmpty2)
        return 1;
    else {
        NSArray *components1 = [ver1 componentsSeparatedByString:@"."];
        NSArray *components2 = [ver2 componentsSeparatedByString:@"."];
 
        int count = [components1 count] > [components2 count] ? [components2 count] : [components1 count];
        for (int i=0; i<count; i++) {
            int num1 = [[components1 objectAtIndex:i] intValue];
            int num2 = [[components2 objectAtIndex:i] intValue];
 
            if (num1 < num2)
                return -1;
            else if (num1 > num2)
                return 1;
            else {
                if ([[components1 objectAtIndex:i] isEqualToString:[components2 objectAtIndex:i]])
                    continue;
                else
                    return [[components1 objectAtIndex:i] compare:[components2 objectAtIndex:i]] == NSOrderedDescending ? 1 : -1;
            }
        }
 
        if ([components1 count] != [components2 count])
            return [components1 count] > [components2 count] ? 1 : -1;
        else
            return 0;
    }
}
 
static NSArray *getInstalledApplications() {
    if (kCFCoreFoundationVersionNumber < 1140.10) {
        NSDictionary *mobileInstallationPlist = [NSDictionary dictionaryWithContentsOfFile:@"/private/var/mobile/Library/Caches/com.apple.mobile.installation.plist"];
        NSDictionary *installedAppDict = (NSDictionary*)[mobileInstallationPlist objectForKey:@"User"];
 
        NSArray * identifiers = [[installedAppDict allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
 
        return identifiers;
    } else {
        Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");
        if (LSApplicationWorkspace_class) {
            LSApplicationWorkspace *workspace = [LSApplicationWorkspace_class performSelector:@selector(defaultWorkspace)];
            if (workspace) {
                NSArray *allApps = [workspace applicationsOfType:0];
                NSMutableArray *identifiers = [NSMutableArray arrayWithCapacity:[allApps count]];
                for (LSApplicationProxy *appBundle in allApps)
                    [identifiers addObject:appBundle.bundleIdentifier];
                return [identifiers sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
            }
        }
    }
    return nil;
}
 
static NSString *formatDictValue(NSObject *object) {
    return object ? (NSString *)object : @"";
}
 
static NSString *getBestString(NSString *main, NSString *minor) {
    return (minor && [minor length] > 0) ? minor : (main ? main : @"");
}
 
static NSDictionary *getInstalledAppInfo(NSString *appIdentifier) {
    if (kCFCoreFoundationVersionNumber < 1140.10) {
        NSDictionary *mobileInstallationPlist = [NSDictionary dictionaryWithContentsOfFile:@"/private/var/mobile/Library/Caches/com.apple.mobile.installation.plist"];
        NSDictionary *installedAppDict = (NSDictionary*)[mobileInstallationPlist objectForKey:@"User"];
 
        NSDictionary *appInfo = [installedAppDict objectForKey:appIdentifier];
        if (appInfo) {
            NSMutableDictionary *info = [NSMutableDictionary dictionaryWithCapacity:8];
            [info setObject:formatDictValue([appInfo objectForKey:@"CFBundleIdentifier"]) forKey:@"APP_ID"];
            [info setObject:formatDictValue([appInfo objectForKey:@"Container"]) forKey:@"BUNDLE_PATH"];
            [info setObject:formatDictValue([appInfo objectForKey:@"Path"]) forKey:@"APP_PATH"];
            [info setObject:formatDictValue([appInfo objectForKey:@"Container"]) forKey:@"DATA_PATH"];
            [info setObject:formatDictValue([appInfo objectForKey:@"CFBundleVersion"]) forKey:@"VERSION"];
            [info setObject:formatDictValue([appInfo objectForKey:@"CFBundleShortVersionString"]) forKey:@"SHORT_VERSION"];
            [info setObject:formatDictValue([appInfo objectForKey:@"CFBundleName"]) forKey:@"NAME"];
            [info setObject:formatDictValue([appInfo objectForKey:@"CFBundleDisplayName"]) forKey:@"DISPLAY_NAME"];
            return info;
        }
    } else {
        Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");
        if (LSApplicationWorkspace_class) {
            LSApplicationWorkspace *workspace = [LSApplicationWorkspace_class performSelector:@selector(defaultWorkspace)];
            if (workspace && [workspace applicationIsInstalled:appIdentifier]) {
                Class LSApplicationProxy_class = objc_getClass("LSApplicationProxy");
                if (LSApplicationProxy_class) {
                    LSApplicationProxy *app = [LSApplicationProxy_class applicationProxyForIdentifier:appIdentifier];
                    if (app) {
                        NSMutableDictionary *info = [NSMutableDictionary dictionaryWithCapacity:9];
                        [info setObject:formatDictValue(app.bundleIdentifier) forKey:@"APP_ID"];
                        [info setObject:formatDictValue([app.bundleContainerURL path]) forKey:@"BUNDLE_PATH"];
                        [info setObject:formatDictValue([app.bundleURL path]) forKey:@"APP_PATH"];
                        [info setObject:formatDictValue([app.dataContainerURL path]) forKey:@"DATA_PATH"];
                        [info setObject:formatDictValue(app.bundleVersion) forKey:@"VERSION"];
                        [info setObject:formatDictValue(app.shortVersionString) forKey:@"SHORT_VERSION"];
                        [info setObject:formatDictValue(app.localizedName) forKey:@"NAME"];
                        [info setObject:formatDictValue(app.localizedShortName) forKey:@"DISPLAY_NAME"];
                        return info;
                    }
                }
            }
        }
    }
    return nil;
}
 
static int installApp(NSString *ipaPath, NSString *ipaId) {
    int ret = -1;
    if (kCFCoreFoundationVersionNumber < 1140.10) {
        void *lib = dlopen(KEY_SDKPATH, RTLD_LAZY);
        if (lib) {
            MobileInstallationInstall install = (MobileInstallationInstall)dlsym(lib, "MobileInstallationInstall");
            if (install)
                ret = install(ipaPath, [NSDictionary dictionaryWithObject:KEY_INSTALL_TYPE forKey:@"ApplicationType"], 0, ipaPath);
            dlclose(lib);
        }
    } else {
        Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");
        if (LSApplicationWorkspace_class) {
            LSApplicationWorkspace *workspace = [LSApplicationWorkspace_class performSelector:@selector(defaultWorkspace)];
            if (workspace && [workspace installApplication:[NSURL fileURLWithPath:ipaPath] withOptions:[NSDictionary dictionaryWithObject:ipaId forKey:@"CFBundleIdentifier"]])
                ret = 0;
        }
    }
    return ret;
}
 
static BOOL uninstallApplication(NSString *appIdentifier) {
    if (kCFCoreFoundationVersionNumber < 1140.10) {
        void *lib = dlopen(KEY_SDKPATH, RTLD_LAZY);
        if (lib) {
            MobileInstallationUninstall uninstall = (MobileInstallationUninstall)dlsym(lib, "MobileInstallationUninstall");
            if (uninstall)
                return 0 == uninstall(appIdentifier, nil, nil);
            dlclose(lib);
        }
    } else {
        Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");
        if (LSApplicationWorkspace_class) {
            LSApplicationWorkspace *workspace = [LSApplicationWorkspace_class performSelector:@selector(defaultWorkspace)];
            if (workspace && [workspace uninstallApplication:appIdentifier withOptions:nil])
                return YES;
        }
 
    }
    return NO;
}
 
int main (int argc, char **argv, char **envp) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 
    freopen("/dev/null", "w", stderr); //Suppress output from NSLog
 
    //Get system info
    SystemVersion = [UIDevice currentDevice].systemVersion;
    NSString *deviceString = [UIDevice currentDevice].model;
    if ([deviceString isEqualToString:@"iPhone"] || [deviceString isEqualToString:@"iPod touch"])
        DeviceModel = 1;
    else if ([deviceString isEqualToString:@"iPad"])
        DeviceModel = 2;
    else
        DeviceModel = 3; //Apple TV maybe?
 
    //Process parameters
    NSArray *arguments = [[NSProcessInfo processInfo] arguments];
 
    if ([arguments count] < 1) {
        [pool release];
        return IPA_FAILED;
    }
 
    NSString *executableName = [[arguments objectAtIndex:0] lastPathComponent];
 
    NSString *helpString = [NSString stringWithFormat:@"Usage: %@ [OPTION]... [FILE]...\n       %@ -{bB} [APP_ID] [-o OUTPUT_PATH]\n       %@ -i [APP_ID]...\n       %@ -l\n       %@ -u [APP_ID]...\n\n\nOptions:\n    -a  Show tool about information.\n    -b  Back up application with given identifier to IPA.\n    -B  Back up application with given identifier and its documents and settings to IPA.\n    -c  Perform a clean install.\n        If the application has already been installed, the existing documents and other resources will be cleared.\n        This implements -n automatically.\n    -d  Delete IPA file(s) after installation.\n    -f  Force installation, do not check capabilities and system version.\n        Installed application may not work properly.\n    -h  Display this usage information.\n    -i  Display information of installed application(s).\n    -l  List identifiers of all installed App Store applications.\n    -n  Do not restore saved documents and other resources.\n    -o  Output IPA to specified path, or the IPA will be saved under /var/mobile/Documents/.\n    -q  Quiet mode, suppress all normal outputs.\n    -Q  Quieter mode, suppress all outputs including errors.\n    -r  Remove iTunesMetadata.plist after installation.\n    -u  Uninstall application with given identifier(s).", executableName, executableName, executableName, executableName, executableName];
 
    NSDate *today = [NSDate date];
 
    NSDateFormatter *currentFormatter = [[NSDateFormatter alloc] init];
 
    [currentFormatter setDateFormat:@"yyyy"];
 
    NSString *aboutString = [NSString stringWithFormat:@"About %@\nInstall IPAs via command line or back up/browse/uninstall installed applications.\nVersion: %@\nAuthor: Merlin Mao\n\nZipArchive from Matt Connolly\nFSSystemHasCapability from Ryan Petrich\n\nCopyright \u00A9 2012%@ Merlin Mao. All rights reserved.", executableName, EXECUTABLE_VERSION, [[currentFormatter stringFromDate:today] isEqualToString:@"2012"] ? @"" : [@"-" stringByAppendingString:[currentFormatter stringFromDate:today]]];
 
    [currentFormatter release];
 
    if ([arguments count] == 1) {
        printf("%s\n", [helpString cStringUsingEncoding:NSUTF8StringEncoding]);
        [pool release];
        return 0;
    }
 
    NSFileManager *fileMgr = [NSFileManager defaultManager];
 
    if ([arguments count] >= 3) {
        NSMutableArray *identifiers = [NSMutableArray array];
 
        NSString *op1 = [arguments objectAtIndex:1];
        if ([op1 isEqualToString:@"-uq"] || [op1 isEqualToString:@"-qu"]) {
            isUninstall = YES;
            quietInstall = 1;
            for (unsigned int i=2; i<[arguments count]; i++)
                [identifiers addObject:[arguments objectAtIndex:i]];
        }
        if ([op1 isEqualToString:@"-uQ"] || [op1 isEqualToString:@"-Qu"]) {
            isUninstall = YES;
            quietInstall = 2;
            for (unsigned int i=2; i<[arguments count]; i++)
                [identifiers addObject:[arguments objectAtIndex:i]];
        }
        NSString *op2 = [arguments objectAtIndex:2];
        if ([op1 isEqualToString:@"-u"]) {
            isUninstall = YES;
            if ([op2 isEqualToString:@"-q"]) {
                quietInstall = 1;
                for (unsigned int i=3; i<[arguments count]; i++)
                    [identifiers addObject:[arguments objectAtIndex:i]];
            }
            else if ([op2 isEqualToString:@"-Q"]) {
                quietInstall = 2;
                for (unsigned int i=3; i<[arguments count]; i++)
                    [identifiers addObject:[arguments objectAtIndex:i]];
            } else {
                for (unsigned int i=2; i<[arguments count]; i++)
                    [identifiers addObject:[arguments objectAtIndex:i]];
            }
        }
        if ([op1 isEqualToString:@"-i"]) {
            isGetInfo = YES;
            for (unsigned int i=2; i<[arguments count]; i++)
                [identifiers addObject:[arguments objectAtIndex:i]];
        }
 
        if ([op2 isEqualToString:@"-u"]) {
            if ([op1 isEqualToString:@"-q"]) {
                isUninstall = YES;
                quietInstall = 1;
                for (unsigned int i=3; i<[arguments count]; i++)
                    [identifiers addObject:[arguments objectAtIndex:i]];
            }
            if ([op1 isEqualToString:@"-Q"]) {
                quietInstall = 2;
                for (unsigned int i=3; i<[arguments count]; i++)
                    [identifiers addObject:[arguments objectAtIndex:i]];
            }
        }
 
        if (isGetInfo) {
            if ([identifiers count] < 1) {
                printf("You must specify at least one application identifier.\n");
                [pool release];
                return IPA_FAILED;
            }
 
            NSArray *installedApps = getInstalledApplications();
 
            for (unsigned int i=0; i<[identifiers count]; i++) {
                NSString *identifier = [identifiers objectAtIndex:i];
                if ([installedApps containsObject:identifier]) {
                    NSDictionary *installedAppInfo = getInstalledAppInfo(identifier);
 
                    NSString *appDirPath = [installedAppInfo objectForKey:@"BUNDLE_PATH"];
                    NSString *appPath = [installedAppInfo objectForKey:@"APP_PATH"];
                    NSString *dataPath = [installedAppInfo objectForKey:@"DATA_PATH"];
                    NSString *appName = [installedAppInfo objectForKey:@"NAME"];
                    NSString *appDisplayName = [installedAppInfo objectForKey:@"DISPLAY_NAME"];
                    NSString *appVersion = [installedAppInfo objectForKey:@"VERSION"];
                    NSString *appShortVersion = [installedAppInfo objectForKey:@"SHORT_VERSION"];
 
                    printf("Identifier: %s\n", [identifier cStringUsingEncoding:NSUTF8StringEncoding]);
                    if ([appVersion length] > 0)
                        printf("Version: %s\n", [appVersion cStringUsingEncoding:NSUTF8StringEncoding]);
                    if ([appShortVersion length] > 0)
                        printf("Short Version: %s\n", [appShortVersion cStringUsingEncoding:NSUTF8StringEncoding]);
                    if ([appName length] > 0)
                        printf("Name: %s\n", [appName cStringUsingEncoding:NSUTF8StringEncoding]);
                    if ([appDisplayName length] > 0)
                        printf("Display Name: %s\n", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding]);
                    if ([appDirPath length] > 0)
                        printf("Bundle: %s\n", [appDirPath cStringUsingEncoding:NSUTF8StringEncoding]);
                    if ([appPath length] > 0)
                        printf("Application: %s\n", [appPath cStringUsingEncoding:NSUTF8StringEncoding]);
                    if ([dataPath length] > 0)
                        printf("Data: %s\n", [dataPath cStringUsingEncoding:NSUTF8StringEncoding]);
                } else {
                    if (quietInstall < 2)
                        printf("Application \"%s\" is not installed.\n", [identifier cStringUsingEncoding:NSUTF8StringEncoding]);
                }
                if (i < [identifiers count] - 1)
                    printf("\n");
            }
            return 0;
        }
 
        if (isUninstall) {
            if ([identifiers count] < 1) {
                printf("You must specify at least one application identifier.\n");
                [pool release];
                return IPA_FAILED;
            } else {
                NSArray *installedApps = getInstalledApplications();
 
                for (unsigned int i=0; i<[identifiers count]; i++) {
                    if ([installedApps containsObject:[identifiers objectAtIndex:i]]) {
                        printf("Removing application \"%s\".\n", [[identifiers objectAtIndex:i] cStringUsingEncoding:NSUTF8StringEncoding]);
                        if (uninstallApplication([identifiers objectAtIndex:i])) {
                            if (quietInstall == 0)
                                printf("Successfully removed application \"%s\".\n", [[identifiers objectAtIndex:i] cStringUsingEncoding:NSUTF8StringEncoding]);
                        } else {
                            if (quietInstall < 2)
                                printf("Failed to remove application \"%s\".\n", [[identifiers objectAtIndex:i] cStringUsingEncoding:NSUTF8StringEncoding]);
                        }
                    } else {
                        if (quietInstall < 2)
                            printf("Application \"%s\" is not installed.\n", [[identifiers objectAtIndex:i] cStringUsingEncoding:NSUTF8StringEncoding]);
                    }
                }
 
                [pool release];
                return 0;
            }
        }
 
        NSString *identifier = nil, *savePath = nil;
        if ([op1 isEqualToString:@"-bq"] || [op1 isEqualToString:@"-qb"]) {
            isBackup = YES;
            quietInstall = 1;
            if ([arguments count] == 5) {
                identifier = [arguments objectAtIndex:2];
                NSString *opOutput = [arguments objectAtIndex:3];
                if (![opOutput isEqualToString:@"-o"]) {
                    printf("Invalid parameters.\n");
                    [pool release];
                    return 0;
                }
                savePath = [arguments objectAtIndex:4];
            } else if ([arguments count] != 3) {
                printf("Invalid parameters.\n");
                [pool release];
                return 0;
            } else
                identifier = [arguments objectAtIndex:2];
        }
        if ([op1 isEqualToString:@"-bQ"] || [op1 isEqualToString:@"-Qb"]) {
            isBackup = YES;
            quietInstall = 2;
            if ([arguments count] == 5) {
                identifier = [arguments objectAtIndex:2];
                NSString *opOutput = [arguments objectAtIndex:3];
                if (![opOutput isEqualToString:@"-o"]) {
                    printf("Invalid parameters.\n");
                    [pool release];
                    return 0;
                }
                savePath = [arguments objectAtIndex:4];
            } else if ([arguments count] != 3) {
                printf("Invalid parameters.\n");
                [pool release];
                return 0;
            } else
                identifier = [arguments objectAtIndex:2];
        }
        if ([op1 isEqualToString:@"-Bq"] || [op1 isEqualToString:@"-qB"]) {
            isBackupFull = YES;
            quietInstall = 1;
            if ([arguments count] == 5) {
                identifier = [arguments objectAtIndex:2];
                NSString *opOutput = [arguments objectAtIndex:3];
                if (![opOutput isEqualToString:@"-o"]) {
                    printf("Invalid parameters.\n");
                    [pool release];
                    return 0;
                }
                savePath = [arguments objectAtIndex:4];
            } else if ([arguments count] != 3) {
                printf("Invalid parameters.\n");
                [pool release];
                return 0;
            } else
                identifier = [arguments objectAtIndex:2];
        }
        if ([op1 isEqualToString:@"-BQ"] || [op1 isEqualToString:@"-QB"]) {
            isBackupFull = YES;
            quietInstall = 2;
            if ([arguments count] == 5) {
                identifier = [arguments objectAtIndex:2];
                NSString *opOutput = [arguments objectAtIndex:3];
                if (![opOutput isEqualToString:@"-o"]) {
                    printf("Invalid parameters.\n");
                    [pool release];
                    return 0;
                }
                savePath = [arguments objectAtIndex:4];
            } else if ([arguments count] != 3) {
                printf("Invalid parameters.\n");
                [pool release];
                return 0;
            } else
                identifier = [arguments objectAtIndex:2];
        }
        if ([op1 isEqualToString:@"-b"] || [op1 isEqualToString:@"-B"]) {
            if ([op1 isEqualToString:@"-b"])
                isBackup = YES;
            else
                isBackupFull = YES;
 
            if ([op2 isEqualToString:@"-q"] || [op2 isEqualToString:@"-Q"]) {
                quietInstall = [op2 isEqualToString:@"-q"] ? 1 : 2;
                if ([arguments count] == 6) {
                    identifier = [arguments objectAtIndex:3];
                    NSString *opOutput = [arguments objectAtIndex:4];
                    if (![opOutput isEqualToString:@"-o"]) {
                        printf("Invalid parameters.\n");
                        [pool release];
                        return 0;
                    }
                    savePath = [arguments objectAtIndex:5];
                } else if ([arguments count] != 4) {
                    printf("Invalid parameters.\n");
                    [pool release];
                    return 0;
                } else
                    identifier = [arguments objectAtIndex:3];
            } else {
                if ([arguments count] == 5) {
                    identifier = [arguments objectAtIndex:2];
                    NSString *opOutput = [arguments objectAtIndex:3];
                    if (![opOutput isEqualToString:@"-o"]) {
                        printf("Invalid parameters.\n");
                        [pool release];
                        return 0;
                    }
                    savePath = [arguments objectAtIndex:4];
                } else if ([arguments count] != 3) {
                    printf("Invalid parameters.\n");
                    [pool release];
                    return 0;
                } else
                    identifier = [arguments objectAtIndex:2];
            }
        }
        if ([op2 isEqualToString:@"-b"] || [op2 isEqualToString:@"-B"]) {
            if ([op1 isEqualToString:@"-q"] || [op1 isEqualToString:@"-Q"]) {
                if ([op2 isEqualToString:@"-b"])
                    isBackup = YES;
                else
                    isBackupFull = YES;
                quietInstall = [op1 isEqualToString:@"-q"] ? 1 : 2;
                if ([arguments count] == 6) {
                    identifier = [arguments objectAtIndex:3];
                    NSString *opOutput = [arguments objectAtIndex:4];
                    if (![opOutput isEqualToString:@"-o"]) {
                        printf("Invalid parameters.\n");
                        [pool release];
                        return 0;
                    }
                    savePath = [arguments objectAtIndex:5];
                } else if ([arguments count] != 4) {
                    printf("Invalid parameters.\n");
                    [pool release];
                    return 0;
                } else
                    identifier = [arguments objectAtIndex:3];
            }
        }
 
        if (isBackup || isBackupFull) {
            if ([identifier length] < 1) {
                printf("You must specify an application identifier.\n");
                [pool release];
                return 0;
            }
 
            if (savePath) {
                if (![savePath hasPrefix:@"/"])
                    savePath = [[fileMgr currentDirectoryPath] stringByAppendingPathComponent:savePath];
 
                savePath = [savePath stringByStandardizingPath];;
            }
 
            if ([fileMgr fileExistsAtPath:savePath]) {
                printf("%s already exists.\n", [savePath cStringUsingEncoding:NSUTF8StringEncoding]);
                [pool release];
                return IPA_FAILED;
            }
 
            NSDictionary *installedAppInfo = getInstalledAppInfo(identifier);
 
            if (!installedAppInfo) {
                if (quietInstall < 2)
                    printf("Application \"%s\" is not installed.\n", [identifier cStringUsingEncoding:NSUTF8StringEncoding]);
                [pool release];
                return IPA_FAILED;
            } else
                printf("Backing up application with identifier \"%s\"...\n", [identifier cStringUsingEncoding:NSUTF8StringEncoding]);
 
            NSString *appDirPath = [installedAppInfo objectForKey:@"BUNDLE_PATH"];
            NSString *appPath = [installedAppInfo objectForKey:@"APP_PATH"];
            NSString *dataPath = [installedAppInfo objectForKey:@"DATA_PATH"];
            NSString *appName = [installedAppInfo objectForKey:@"NAME"];
            NSString *appDisplayName = [installedAppInfo objectForKey:@"DISPLAY_NAME"];
            NSString *appVersion = [installedAppInfo objectForKey:@"VERSION"];
            NSString *appShortVersion = [installedAppInfo objectForKey:@"SHORT_VERSION"];
            if (!appDisplayName || [appDisplayName length] < 1)
                appDisplayName = appName;
            if (!appShortVersion || [appShortVersion length] < 1)
                appShortVersion = appVersion;
 
            BOOL isDirectory;
            if (![fileMgr fileExistsAtPath:appDirPath isDirectory:&isDirectory]) {
                if (quietInstall < 2)
                    printf("Cannot find %s.\n", [appDirPath cStringUsingEncoding:NSUTF8StringEncoding]);
                [pool release];
                return IPA_FAILED;
            }
            if (!isDirectory) {
                if (quietInstall < 2)
                    printf("%s is not a directory.\n", [appDirPath cStringUsingEncoding:NSUTF8StringEncoding]);
                [pool release];
                return IPA_FAILED;
            }
            if (![fileMgr fileExistsAtPath:appPath isDirectory:&isDirectory]) {
                if (quietInstall < 2)
                    printf("Cannot find %s.\n", [appPath cStringUsingEncoding:NSUTF8StringEncoding]);
                [pool release];
                return IPA_FAILED;
            }
            if (!isDirectory) {
                if (quietInstall < 2)
                    printf("%s is not a directory.\n", [appPath cStringUsingEncoding:NSUTF8StringEncoding]);
                [pool release];
                return IPA_FAILED;
            }
            if (isBackupFull) {
                if (![fileMgr fileExistsAtPath:dataPath isDirectory:&isDirectory]) {
                    if (quietInstall < 2)
                        printf("Cannot find %s.\n", [dataPath cStringUsingEncoding:NSUTF8StringEncoding]);
                    [pool release];
                    return IPA_FAILED;
                }
                if (!isDirectory) {
                    if (quietInstall < 2)
                        printf("%s is not a directory.\n", [dataPath cStringUsingEncoding:NSUTF8StringEncoding]);
                    [pool release];
                    return IPA_FAILED;
                }
            }
 
            //Clean before
            NSArray *filesInTemp = [fileMgr contentsOfDirectoryAtPath:NSTemporaryDirectory() error:nil];
            for (NSString *file in filesInTemp) {
                file = [NSTemporaryDirectory() stringByAppendingPathComponent:[file lastPathComponent]];
                if ([[file lastPathComponent] hasPrefix:@"com.autopear.ipainstaller."] && ![fileMgr removeItemAtPath:file error:nil]) {
                    if (quietInstall < 2)
                        printf("Failed to delete %s.\n", [file cStringUsingEncoding:NSUTF8StringEncoding]);
                }
            }
 
            //Create temp path
            NSString *workPath = nil;
            while (YES) {
                workPath = [NSString stringWithFormat:@"com.autopear.ipainstaller.%@", randomStringInLength(6)];
                workPath = [NSTemporaryDirectory() stringByAppendingPathComponent:workPath];
                if (![fileMgr fileExistsAtPath:workPath])
                    break;
            }
 
            if(![fileMgr createDirectoryAtPath:workPath withIntermediateDirectories:YES attributes:nil error:NULL] ) {
                if (quietInstall < 2)
                    printf("Failed to create workspace.\n");
                [pool release];
                return IPA_FAILED;
            }
 
            ZipArchive *ipaArchive = [[ZipArchive alloc] init];
            // APPEND_STATUS_ADDINZIP = 2
            if (![ipaArchive openZipFile2:[workPath stringByAppendingPathComponent:@"temp.zip"] withZipModel:APPEND_STATUS_ADDINZIP]) {
                [ipaArchive release];
                if (quietInstall < 2)
                    printf("Failed to create IPA file.\n");
 
                if (!removeAllContentsUnderPath(workPath)) {
                    if (quietInstall < 2)
                        printf("Failed to clean caches.\n");
                }
 
                [pool release];
                return IPA_FAILED;
            }
 
            if (![ipaArchive addDirectoryToZip:appPath toPathInZip:[NSString stringWithFormat:@"Payload/%@/", [appPath lastPathComponent]]]) {
                if (quietInstall < 2)
                    printf("Failed to create ipa file.\n");
                [ipaArchive release];
 
                if (!removeAllContentsUnderPath(workPath)) {
                    if (quietInstall < 2)
                        printf("Failed to clean caches.\n");
                }
 
                [pool release];
                return IPA_FAILED;
            }
 
            if ([fileMgr fileExistsAtPath:[appDirPath stringByAppendingPathComponent:@"iTunesArtwork"]])
                [ipaArchive addFileToZip:[appDirPath stringByAppendingPathComponent:@"iTunesArtwork"] newname:@"iTunesArtwork"];
 
            if ([fileMgr fileExistsAtPath:[appDirPath stringByAppendingPathComponent:@"iTunesMetadata.plist"]])
                [ipaArchive addFileToZip:[appDirPath stringByAppendingPathComponent:@"iTunesMetadata.plist"] newname:@"iTunesMetadata.plist"];
 
            if (isBackupFull) {
                if (quietInstall == 0)
                    printf("Backing up application data...\n");
 
                NSArray *dataContents = [fileMgr contentsOfDirectoryAtPath:dataPath error:nil];
                for (NSString *file in dataContents) {
                    if ([file hasSuffix:@".app"] ||
                        [file isEqualToString:@".com.apple.mobile_container_manager.metadata.plist"] ||
                        [file isEqualToString:@".com.apple.mobileinstallation.placeholder"] ||
                        [file isEqualToString:@".GlobalPreferences.plist"] ||
                        [file isEqualToString:@"com.apple.PeoplePicker.plist"] ||
                        [file isEqualToString:@"iTunesArtwork"] ||
                        [file isEqualToString:@"iTunesMetadata.plist"])
                        continue;
 
                    if ([file isEqualToString:@"Library"]){
                        BOOL globalMoved = NO;
                        if ([fileMgr moveItemAtPath:[dataPath stringByAppendingPathComponent:@"Library/Preferences/.GlobalPreferences.plist"] toPath:[dataPath stringByAppendingPathComponent:@".GlobalPreferences.plist"] error:nil])
                            globalMoved = YES;
                        BOOL pickerMoved = NO;
                        if ([fileMgr moveItemAtPath:[dataPath stringByAppendingPathComponent:@"Library/Preferences/com.apple.PeoplePicker.plist"] toPath:[dataPath stringByAppendingPathComponent:@"com.apple.PeoplePicker.plist"] error:nil])
                            pickerMoved = YES;
 
                        [ipaArchive addDirectoryToZip:[dataPath stringByAppendingPathComponent:@"Library"] toPathInZip:@"Container/Library/"];
                        if (globalMoved)
                            [fileMgr moveItemAtPath:[dataPath stringByAppendingPathComponent:@".GlobalPreferences.plist"] toPath:[dataPath stringByAppendingPathComponent:@"Library/Preferences/.GlobalPreferences.plist"] error:nil];
                        if (pickerMoved)
                            [fileMgr moveItemAtPath:[dataPath stringByAppendingPathComponent:@"com.apple.PeoplePicker.plist"] toPath:[dataPath stringByAppendingPathComponent:@"Library/Preferences/com.apple.PeoplePicker.plist"] error:nil];
                    } else {
                        NSString *sourcePath = [dataPath stringByAppendingPathComponent:file];
                        BOOL isDir;
                        if ([fileMgr fileExistsAtPath:sourcePath isDirectory:&isDir] && isDir)
                            [ipaArchive addDirectoryToZip:sourcePath toPathInZip:[NSString stringWithFormat:@"Container/%@/", file]];
                        else
                            [ipaArchive addFileToZip:sourcePath newname:[NSString stringWithFormat:@"Container/%@/", file]];
                    }
                }
            }
 
            [ipaArchive release];
 
            if (savePath) {
                NSString *saveDir = [savePath stringByDeletingLastPathComponent];
 
                BOOL isDirectory;
                if ([fileMgr fileExistsAtPath:saveDir isDirectory:&isDirectory]) {
                    if (!isDirectory) {
                        if (quietInstall < 2)
                            printf("%s is not a directory.\n", [saveDir cStringUsingEncoding:NSUTF8StringEncoding]);
 
                        if (!removeAllContentsUnderPath(workPath)) {
                            if (quietInstall < 2)
                                printf("Failed to clean caches.\n");
                        }
 
                        [pool release];
                        return IPA_FAILED;
                    }
                } else {
                    if(![fileMgr createDirectoryAtPath:saveDir withIntermediateDirectories:YES attributes:nil error:NULL] ) {
                        if (quietInstall < 2)
                            printf("Failed to create directory %s.\n", [saveDir cStringUsingEncoding:NSUTF8StringEncoding]);
 
                        if (!removeAllContentsUnderPath(workPath)) {
                            if (quietInstall < 2)
                                printf("Failed to clean caches.\n");
                        }
 
                        [pool release];
                        return IPA_FAILED;
                    }
 
                    //Set root folder's attributes
                    NSDictionary *directoryAttributes = [fileMgr attributesOfItemAtPath:saveDir error:nil];
                    NSMutableDictionary *defaultDirectoryAttributes = [NSMutableDictionary dictionaryWithCapacity:[directoryAttributes count]];
                    [defaultDirectoryAttributes setDictionary:directoryAttributes];
 
                    [defaultDirectoryAttributes setObject:[NSNumber numberWithInt:501] forKey:NSFileOwnerAccountID];
                    [defaultDirectoryAttributes setObject:@"mobile" forKey:NSFileOwnerAccountName];
                    [defaultDirectoryAttributes setObject:[NSNumber numberWithInt:501] forKey:NSFileGroupOwnerAccountID];
                    [defaultDirectoryAttributes setObject:@"mobile" forKey:NSFileGroupOwnerAccountName];
 
                    [defaultDirectoryAttributes setObject:[NSNumber numberWithShort:0755] forKey:NSFilePosixPermissions];
 
                    [fileMgr setAttributes:defaultDirectoryAttributes ofItemAtPath:saveDir error:nil];
                }
 
                //Move
                if (![fileMgr moveItemAtPath:[workPath stringByAppendingPathComponent:@"temp.zip"] toPath:savePath error:nil]) {
                    if (quietInstall < 2)
                        printf("Failed to create IPA file.\n");
 
                    if (!removeAllContentsUnderPath(workPath)) {
                        if (quietInstall < 2)
                            printf("Failed to clean caches.\n");
                    }
 
                    [pool release];
                    return IPA_FAILED;
                }
 
                if (!removeAllContentsUnderPath(workPath)) {
                    if (quietInstall < 2)
                        printf("Failed to clean caches.\n");
                }
 
                if (quietInstall == 0)
                    printf("The application has been backed up as %s.\n", [savePath cStringUsingEncoding:NSUTF8StringEncoding]);
 
                [pool release];
                return 0;
            } else {
                NSString *nameBase;
                if (isBackup)
                    nameBase = [NSString stringWithFormat:@"%@ (%@) v%@", getBestString(appName, appDisplayName), identifier, getBestString(appVersion, appShortVersion)];
                else
                    nameBase = [NSString stringWithFormat:@"%@ (%@) v%@ (Full)", getBestString(appName, appDisplayName), identifier, getBestString(appVersion, appShortVersion)];
                NSString *saveDir = @"/private/var/mobile/Documents";
 
                if (![fileMgr fileExistsAtPath:saveDir]) {
                    if(![fileMgr createDirectoryAtPath:saveDir withIntermediateDirectories:YES attributes:nil error:NULL] ) {
                        if (quietInstall < 2)
                            printf("Failed to create /var/mobile/Documents.\n");
 
                        if (!removeAllContentsUnderPath(workPath)) {
                            if (quietInstall < 2)
                                printf("Failed to clean caches.\n");
                        }
 
                        [pool release];
                        return IPA_FAILED;
                    }
 
                    //Set root folder's attributes
                    NSDictionary *directoryAttributes = [fileMgr attributesOfItemAtPath:saveDir error:nil];
                    NSMutableDictionary *defaultDirectoryAttributes = [NSMutableDictionary dictionaryWithCapacity:[directoryAttributes count]];
                    [defaultDirectoryAttributes setDictionary:directoryAttributes];
 
                    [defaultDirectoryAttributes setObject:[NSNumber numberWithInt:501] forKey:NSFileOwnerAccountID];
                    [defaultDirectoryAttributes setObject:@"mobile" forKey:NSFileOwnerAccountName];
                    [defaultDirectoryAttributes setObject:[NSNumber numberWithInt:501] forKey:NSFileGroupOwnerAccountID];
                    [defaultDirectoryAttributes setObject:@"mobile" forKey:NSFileGroupOwnerAccountName];
 
                    [defaultDirectoryAttributes setObject:[NSNumber numberWithShort:0755] forKey:NSFilePosixPermissions];
 
                    [fileMgr setAttributes:defaultDirectoryAttributes ofItemAtPath:saveDir error:nil];
                }
 
                //Move
                NSString *ipaPath = [[NSString stringWithFormat:@"%@/%@.ipa", saveDir, nameBase] stringByStandardizingPath];
                if ([fileMgr fileExistsAtPath:ipaPath]) {
                    for (int i=1; ; i++) {
                        ipaPath = [NSString stringWithFormat:@"%@/%@ %d.ipa", saveDir, nameBase, i];
                        if (![fileMgr fileExistsAtPath:ipaPath])
                            break;
                    }
                }
 
                if (![fileMgr moveItemAtPath:[workPath stringByAppendingPathComponent:@"temp.zip"] toPath:ipaPath error:nil]) {
                    if (quietInstall < 2)
                        printf("Failed to create IPA file.\n");
 
                    if (!removeAllContentsUnderPath(workPath)) {
                        if (quietInstall < 2)
                            printf("Failed to clean caches.\n");
                    }
 
                    [pool release];
                    return IPA_FAILED;
                }
 
                if (!removeAllContentsUnderPath(workPath)) {
                    if (quietInstall < 2)
                        printf("Failed to clean caches.\n");
                }
 
                if (quietInstall == 0)
                    printf("The application has been backed up as %s.\n", [ipaPath cStringUsingEncoding:NSUTF8StringEncoding]);
 
                [pool release];
                return 0;
            }
        }
    }
 
    NSMutableArray *ipaFiles = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray *filesNotFound = [NSMutableArray arrayWithCapacity:0];
    BOOL noParameters = NO;
    BOOL showHelp = NO;
    BOOL showAbout = NO;
    for (unsigned int i=1; i<[arguments count]; i++) {
        NSString *arg = [arguments objectAtIndex:i];
        if ([arg hasPrefix:@"-" ]) {
            if ([arg length] < 2 || noParameters) {
                printf("Invalid parameters.\n");
                [pool release];
                return IPA_FAILED;
            }
 
            for (unsigned int j=1; j<[arg length]; j++) {
                NSString *p = [arg substringWithRange:NSMakeRange(j, 1)];
                if ([p isEqualToString:@"u"])
                    isUninstall = YES;
                else if ([p isEqualToString:@"l"])
                    isListing = YES;
                else if ([p isEqualToString:@"b"]) {
                    if (isBackupFull) {
                        printf("Parameter b and B cannot be specified at the same time.\n");
                        [pool release];
                        return IPA_FAILED;
                    }
                    isBackup = YES;
                } else if ([p isEqualToString:@"B"]) {
                    if (isBackup) {
                        printf("Parameter -b and -B cannot be specified at the same time.\n");
                        [pool release];
                        return IPA_FAILED;
                    }
                    isBackupFull = YES;
                } else if ([p isEqualToString:@"a"])
                    showAbout = YES;
                else if ([p isEqualToString:@"c"])
                    cleanInstall = YES;
                else if ([p isEqualToString:@"d"])
                    deleteFile = YES;
                else if ([p isEqualToString:@"i"] || [p isEqualToString:@"I"])
                    isGetInfo = YES;
                else if ([p isEqualToString:@"f"])
                    forceInstall = YES;
                else if ([p isEqualToString:@"h"])
                    showHelp = YES;
                else if ([p isEqualToString:@"n"])
                    notRestore = YES;
                else if ([p isEqualToString:@"q"]) {
                    if (quietInstall != 0) {
                        printf("Parameter -q and -Q cannot be specified at the same time.\n");
                        [pool release];
                        return IPA_FAILED;
                    }
                    quietInstall = 1;
                } else if ([p isEqualToString:@"Q"]) {
                    if (quietInstall != 0) {
                        printf("Parameter -q and -Q cannot be specified at the same time.\n");
                        [pool release];
                        return IPA_FAILED;
                    }
                    quietInstall = 2;
                } else if ([p isEqualToString:@"r"])
                    removeMetadata = YES;
                else if ([p isEqualToString:@"o"]) {
                    if (!isBackup && !isBackupFull) {
                        printf("You must specify -b or -B before -o.\n");
                        [pool release];
                        return IPA_FAILED;
                    }
                } else {
                    printf("Invalid parameter '%s'.\n", [p cStringUsingEncoding:NSUTF8StringEncoding]);
                    [pool release];
                    return IPA_FAILED;
                }
            }
        } else {
            if (!isBackup && !isBackupFull) {
                noParameters = YES;
                NSURL *url = [NSURL fileURLWithPath:arg isDirectory:NO];
                BOOL isDirectory;
                if (url && [fileMgr fileExistsAtPath:[[url absoluteURL] path] isDirectory:&isDirectory]) {
                    if (isDirectory)
                        [filesNotFound addObject:arg];
                    else
                        [ipaFiles addObject:[[url absoluteURL] path]]; //File exists
                } else
                    [filesNotFound addObject:arg];
            }
        }
    }
 
    if (isListing) {
        getInstalledApplications();
        if ([arguments count] != 2) {
            printf("Invalid parameters.\n");
            [pool release];
            return IPA_FAILED;
        } else {
            NSArray * identifiers = getInstalledApplications();
 
            for (unsigned int i=0; i<[identifiers count]; i++)
                printf("%s\n", [(NSString *)[identifiers objectAtIndex:i] cStringUsingEncoding:NSUTF8StringEncoding]);
            [pool release];
            return 0;
        }
    }
 
    if ((showAbout && showHelp) ||
        ((showAbout || showHelp) &&
         (cleanInstall ||
          deleteFile ||
          forceInstall ||
          notRestore ||
          quietInstall != 0 ||
          removeMetadata ||
          ([ipaFiles count] + [filesNotFound count] > 0)))) {
        printf("Invalid parameters.\n");
        [pool release];
        return IPA_FAILED;
    }
 
    if (showHelp) {
        printf("%s\n", [helpString cStringUsingEncoding:NSUTF8StringEncoding]);
        [pool release];
        return 0;
    }
 
    if (showAbout) {
        printf("%s\n", [aboutString cStringUsingEncoding:NSUTF8StringEncoding]);
        [pool release];
        return 0;
    }
 
    for (unsigned int i=0; i<[filesNotFound count]; i++) {
        if (quietInstall < 2)
            printf("File not found at path: %s.\n", [[filesNotFound objectAtIndex:i] cStringUsingEncoding:NSUTF8StringEncoding]);
    }
 
    if ([ipaFiles count] < 1) {
        if (quietInstall < 2)
            printf("Please specify any IPA file(s) to install.\n");
        [pool release];
        return IPA_FAILED;
    }
 
    if (cleanInstall)
        notRestore = YES;
    if (quietInstall == 0 && cleanInstall)
        printf("Clean installation enabled.\n");
    if (quietInstall == 0 && forceInstall)
        printf("Force installation enabled.\n");
    if (quietInstall == 0 && notRestore)
        printf("Will not restore any saved documents and other resources.\n");
    if (quietInstall == 0 && removeMetadata)
        printf("iTunesMetadata.plist will be removed after installation.\n");
    if (quietInstall == 0 && deleteFile) {
        if ([ipaFiles count] == 1)
            printf("%s will be deleted after installation.\n", [[[ipaFiles objectAtIndex:0] lastPathComponent] cStringUsingEncoding:NSUTF8StringEncoding]);
        else
            printf("IPA files will be deleted after installation.\n");
    }
 
    if (quietInstall == 0 && (cleanInstall || forceInstall || notRestore || removeMetadata || deleteFile))
        printf("\n");
 
    NSArray *filesInTemp = [fileMgr contentsOfDirectoryAtPath:NSTemporaryDirectory() error:nil];
    for (NSString *file in filesInTemp) {
        file = [NSTemporaryDirectory() stringByAppendingPathComponent:[file lastPathComponent]];
        if ([[file lastPathComponent] hasPrefix:@"com.autopear.ipainstaller."] && ![fileMgr removeItemAtPath:file error:nil]) {
            if (quietInstall < 2)
                printf("Failed to delete %s.\n", [file cStringUsingEncoding:NSUTF8StringEncoding]);
        }
    }
 
    NSString *workPath = nil;
    while (YES) {
        workPath = [NSString stringWithFormat:@"com.autopear.ipainstaller.%@", randomStringInLength(6)];
        workPath = [NSTemporaryDirectory() stringByAppendingPathComponent:workPath];
        if (![fileMgr fileExistsAtPath:workPath])
            break;
    }
 
    if(![fileMgr createDirectoryAtPath:workPath withIntermediateDirectories:YES attributes:nil error:NULL]) {
        if (quietInstall < 2)
            printf("Failed to create workspace.\n");
        [pool release];
        return IPA_FAILED;
    }
 
    NSString *installPath = [workPath stringByAppendingPathComponent:@"tmp.install.ipa"];
 
    int successfulInstalls = 0;
 
    for (unsigned i=0; i<[ipaFiles count]; i++) {
        //Before installation, make a clean workspace
        if (!removeAllContentsUnderPath(workPath)) {
            if (quietInstall < 2)
                printf("Failed to create workspace.\n");
            [pool release];
            return IPA_FAILED;
        }
 
        NSString *ipa = [ipaFiles objectAtIndex:i];
        if (quietInstall == 0)
            printf("Analyzing %s...\n", [[ipa lastPathComponent] cStringUsingEncoding:NSUTF8StringEncoding]);
 
        BOOL isValidIPA = YES;
        BOOL hasContainer = NO;
        NSString *pathInfoPlist = nil;
        NSString *infoPath = nil;
        while (YES) {
            pathInfoPlist = [workPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.Info.plist", randomStringInLength(6)]];
            if (![fileMgr fileExistsAtPath:pathInfoPlist])
                break;
        }
 
        ZipArchive *ipaArchive = [[ZipArchive alloc] init];
        if ([ipaArchive unzipOpenFile:[ipaFiles objectAtIndex:i]]) {
            NSMutableArray *array = [ipaArchive getZipFileContents];
            NSMutableArray *infoStrings = [NSMutableArray arrayWithCapacity:0];
            NSString *appPathName = nil;
 
            int cnt = 0;
            for (unsigned int j=0; j<[array count]; j++) {
                NSString *name = [array objectAtIndex:j];
                NSArray *components = [name pathComponents];
                if ([components count] > 1 && [[components objectAtIndex:0] isEqualToString:@"Container"])
                    hasContainer = YES;
                else {
                    //Extract Info.plist
                    if ([components count] == 3 &&
                        [[components objectAtIndex:0] isEqualToString:@"Payload"] &&
                        [[components objectAtIndex:1] hasSuffix:@".app"] &&
                        [[components objectAtIndex:2] isEqualToString:@"Info.plist"]) {
                        appPathName = [@"Payload" stringByAppendingPathComponent:[components objectAtIndex:1]];
                        infoPath = name;
                        cnt++;
                    }
 
                    //Extract InfoPlist.strings if available
                    if ([components count] == 4 &&
                        [[components objectAtIndex:0] isEqualToString:@"Payload"] &&
                        [[components objectAtIndex:1] hasSuffix:@".app"] &&
                        [[components objectAtIndex:2] hasSuffix:@".lproj"] &&
                        [[components objectAtIndex:3] isEqualToString:@"InfoPlist.strings"]) {
                        [infoStrings addObject:[components objectAtIndex:2]];
                    }
                }
            }
            if (cnt != 1)
                isValidIPA = NO;
 
            if (isValidIPA) {
                //Unzip Info.plist
                [ipaArchive unzipFileWithName:infoPath toPath:pathInfoPlist overwrite:YES];
 
                //Unzip all InfoPlist.strings
                for (unsigned int j=0; j<[infoStrings count]; j++) {
                    NSString *lprojPath = [[workPath stringByAppendingPathComponent:@"localizations"] stringByAppendingPathComponent:[infoStrings objectAtIndex:j]];
                    if ([fileMgr createDirectoryAtPath:lprojPath withIntermediateDirectories:YES attributes:nil error:NULL]) {
                        //Unzip to this directory
                        [ipaArchive unzipFileWithName:[[appPathName stringByAppendingPathComponent:[infoStrings objectAtIndex:j]] stringByAppendingPathComponent:@"InfoPlist.strings"] toPath:[lprojPath stringByAppendingPathComponent:@"InfoPlist.strings"] overwrite:YES];
                    }
                }
            }
            [ipaArchive unzipCloseFile];
        } else
            isValidIPA = NO;
        [ipaArchive release];
 
        if (!isValidIPA) {
            if (quietInstall < 2)
                printf("%s is not a valid IPA.%s", [[ipaFiles objectAtIndex:i] cStringUsingEncoding:NSUTF8StringEncoding], (i == [ipaFiles count] - 1) ? "\n" : "\n\n");
 
            if (!removeAllContentsUnderPath(workPath)) {
                if (quietInstall < 2)
                    printf("Failed to clean caches.\n");
            }
 
            continue;
        }
 
        NSString *appIdentifier = nil;
        NSString *appDisplayName = nil;
        NSString *appVersion = nil;
        NSString *appShortVersion = nil;
        NSString *minSysVersion = nil;
        NSMutableArray *supportedDeives = nil;
        id requiredCapabilities = nil;
 
        NSMutableDictionary *infoDict = [NSMutableDictionary dictionaryWithContentsOfFile:pathInfoPlist];
 
        if (infoDict) {
            appIdentifier = [infoDict objectForKey:@"CFBundleIdentifier"];
            appVersion = [infoDict objectForKey:@"CFBundleVersion"];
            appShortVersion = [infoDict objectForKey:@"CFBundleShortVersionString"];
            minSysVersion = [infoDict objectForKey:@"MinimumOSVersion"];
            supportedDeives = [infoDict objectForKey:@"UIDeviceFamily"];
            requiredCapabilities = [infoDict objectForKey:@"UIRequiredDeviceCapabilities"];
 
            appDisplayName = [infoDict objectForKey:@"CFBundleDisplayName"] ? [infoDict objectForKey:@"CFBundleDisplayName"] : [infoDict objectForKey:@"CFBundleName"];
 
            //Obtain localized display name
            BOOL isDirectory;
            if ([fileMgr fileExistsAtPath:[workPath stringByAppendingPathComponent:@"localizations"] isDirectory:&isDirectory]) {
                if (isDirectory) {
                    NSBundle *localizedBundle = [NSBundle bundleWithPath:[workPath stringByAppendingPathComponent:@"localizations"]];
 
                    if ([localizedBundle localizedStringForKey:@"CFBundleDisplayName" value:nil table:@"InfoPlist"])
                        appDisplayName = [localizedBundle localizedStringForKey:@"CFBundleDisplayName" value:appDisplayName table:@"InfoPlist"];
                    else
                        appDisplayName = [localizedBundle localizedStringForKey:@"CFBundleName" value:appDisplayName table:@"InfoPlist"];
 
                    //Delete the directory
                    [fileMgr removeItemAtPath:[workPath stringByAppendingPathComponent:@"localizations"] error:nil];
                }
            }
        } else {
            if (quietInstall < 2)
                printf("%s is not a valid IPA.%s", [[ipaFiles objectAtIndex:i] cStringUsingEncoding:NSUTF8StringEncoding], (i == [ipaFiles count] - 1) ? "\n" : "\n\n");
 
            if (!removeAllContentsUnderPath(workPath)) {
                if (quietInstall < 2)
                    printf("Failed to clean caches.\n");
            }
 
            continue;
        }
 
        if (!appIdentifier || !appDisplayName || !appVersion) {
            if (quietInstall < 2)
                printf("%s is not a valid IPA.%s", [[ipaFiles objectAtIndex:i] cStringUsingEncoding:NSUTF8StringEncoding], (i == [ipaFiles count] - 1) ? "\n" : "\n\n");
 
            if (!removeAllContentsUnderPath(workPath)) {
                if (quietInstall < 2)
                    printf("Failed to clean caches.\n");
            }
 
            continue;
        }
 
        //Make a copy of extracted Info.plist
        NSString *pathOriginalInfoPlist = [NSString stringWithFormat:@"%@.original", pathInfoPlist];
        if ([fileMgr fileExistsAtPath:pathOriginalInfoPlist]) {
            if (![fileMgr removeItemAtPath:pathOriginalInfoPlist error:nil]) {
                if (![fileMgr copyItemAtPath:pathInfoPlist toPath:pathOriginalInfoPlist error:nil]) {
                    //Force installation has to be disabled.
                    if (forceInstall && quietInstall < 2)
                        printf("Force installation has to be disabled.\n");
                    forceInstall = NO;
                }
            }
        } else {
            if (![fileMgr copyItemAtPath:pathInfoPlist toPath:pathOriginalInfoPlist error:nil]) {
                //Force installation has to be disabled.
                if (forceInstall && quietInstall < 2)
                    printf("Force installation has to be disabled.\n");
                forceInstall = NO;
            }
        }
 
        //Check installed stats
        NSDictionary *installedAppDict = getInstalledAppInfo(appIdentifier);
 
        BOOL appAlreadyInstalled = NO;
        if (installedAppDict) {
            appAlreadyInstalled = YES;
 
            NSString *installedVerion = [installedAppDict objectForKey:@"VERSION"];
            NSString *installedShortVersion = [installedAppDict objectForKey:@"SHORT_VERSION"];
 
            if (installedShortVersion != nil && appShortVersion != nil) {
                if (versionCompare(installedShortVersion, appShortVersion) == 1) {
                    //Skip to avoid overriding a new version
                    if (forceInstall) {
                        if (quietInstall == 0)
                            printf("%s (v%s) is already installed. Will force to downgrade.%s", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding], [installedShortVersion cStringUsingEncoding:NSUTF8StringEncoding], (i == [ipaFiles count] - 1) ? "\n" : "\n\n");
                    } else {
                        if (quietInstall < 2)
                            printf("%s (v%s) is already installed. You may use -f parameter to force downgrade.%s", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding], [installedShortVersion cStringUsingEncoding:NSUTF8StringEncoding], (i == [ipaFiles count] - 1) ? "\n" : "\n\n");
 
                        if (!removeAllContentsUnderPath(workPath)) {
                            if (quietInstall < 2)
                                printf("Failed to clean caches.\n");
                        }
 
                        continue;
                    }
                }
            } else {
                if (versionCompare(installedVerion, appVersion) == 1) {
                    //Skip to avoid overriding a new version
                    if (forceInstall) {
                        if (quietInstall == 0)
                            printf("%s (v%s) is already installed. Will force to downgrade.%s", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding], [installedVerion cStringUsingEncoding:NSUTF8StringEncoding], (i == [ipaFiles count] - 1) ? "\n" : "\n\n");
                    } else {
                        if (quietInstall < 2)
                            printf("%s (v%s) is already installed. You may use -f parameter to force downgrade.%s", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding], [installedVerion cStringUsingEncoding:NSUTF8StringEncoding], (i == [ipaFiles count] - 1) ? "\n" : "\n\n");
                        if (!removeAllContentsUnderPath(workPath)) {
                            if (quietInstall < 2)
                                printf("Failed to clean caches.\n");
                        }
 
                        continue;
                    }
                }
            }
        }
 
        BOOL shouldUpdateInfoPlist = NO;
 
        //Check device family
        BOOL supportiPhone = NO;
        BOOL supportiPad = NO;
        BOOL supportAppleTV = NO;
        if (!supportedDeives || [supportedDeives count] == 0) {
            supportiPhone = YES;
            supportiPad = YES;
            supportAppleTV = YES;
        } else {
            for (unsigned int j=0; j<[supportedDeives count]; j++) {
                int d =[[supportedDeives objectAtIndex:j] intValue];
                if (d == 1) {
                    supportiPhone = YES;
                    supportiPad = YES;
                }
                if (d == 2)
                    supportiPad = YES;
                if (d == 3)
                    supportAppleTV = YES;
            }
        }
 
        NSString *supportedDeivesString = nil;
        if (!supportiPhone && supportiPad && !supportAppleTV)
            supportedDeivesString = @"iPad";
        else if (!supportiPhone && !supportiPad && supportAppleTV)
            supportedDeivesString = @"Apple TV";
        else if (supportiPhone && supportiPad && !supportAppleTV)
            supportedDeivesString = @"iPhone, iPod touch or iPad";
        else if (supportiPhone && !supportiPad && supportAppleTV)
            supportedDeivesString = @"iPhone, iPod touch or Apple TV";
        else if (!supportiPhone && supportiPad && supportAppleTV)
            supportedDeivesString = @"iPad or Apple TV";
        else if (supportiPhone && !supportiPad && !supportAppleTV)
            supportedDeivesString = @"iPhone or iPod touch"; //Should not reach here, normally support iPhone should support iPad too
        else
            supportedDeivesString = @"iPhone, iPod touch, iPad or Apple TV"; //Should not reach here
 
        if ((DeviceModel == 1 && !supportiPhone) || //Not support iPhone / iPod touch
            (DeviceModel == 2 && !supportiPad) || //Not support iPad
            (DeviceModel == 3 && !supportAppleTV)) { //Not support Apple TV
            //Device not supported
            if (forceInstall) {
                if (quietInstall == 0)
                    printf("%s (v%s) requires %s while your device is %s.%s", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding], [(appShortVersion ? appShortVersion : appVersion) cStringUsingEncoding:NSUTF8StringEncoding], [supportedDeivesString cStringUsingEncoding:NSUTF8StringEncoding], [deviceString cStringUsingEncoding:NSUTF8StringEncoding], (i == [ipaFiles count] - 1) || forceInstall ? "\n" : "\n\n");
 
                [supportedDeives addObject:[NSNumber numberWithInt:DeviceModel]];
                [infoDict setObject:[supportedDeives sortedArrayUsingSelector:@selector(compare:)] forKey:@"UIDeviceFamily"];
                shouldUpdateInfoPlist = YES;
            } else {
                if (quietInstall < 2)
                    printf("%s (v%s) requires %s while your device is %s.%s", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding], [(appShortVersion ? appShortVersion : appVersion) cStringUsingEncoding:NSUTF8StringEncoding], [supportedDeivesString cStringUsingEncoding:NSUTF8StringEncoding], [deviceString cStringUsingEncoding:NSUTF8StringEncoding], (i == [ipaFiles count] - 1) || forceInstall ? "\n" : "\n\n");
 
                if (!removeAllContentsUnderPath(workPath)) {
                    if (quietInstall < 2)
                        printf("Failed to clean caches.\n");
                }
 
                continue;
            }
        }
 
        //Check minimun system requirement
        if (minSysVersion && versionCompare(minSysVersion, SystemVersion) == 1) {
            //System version is less than the min required version
            if (forceInstall) {
                if (quietInstall == 0)
                    printf("%s (v%s) requires iOS %s while your system is %s.%s", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding], [(appShortVersion ? appShortVersion : appVersion) cStringUsingEncoding:NSUTF8StringEncoding], [minSysVersion cStringUsingEncoding:NSUTF8StringEncoding], [SystemVersion cStringUsingEncoding:NSUTF8StringEncoding], (i == [ipaFiles count] - 1) || forceInstall ? "\n" : "\n\n");
 
                [infoDict setObject:SystemVersion forKey:@"MinimumOSVersion"];
                shouldUpdateInfoPlist = YES;
            } else {
                if (quietInstall < 2)
                    printf("%s (v%s) requires iOS %s while your system is %s.%s", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding], [(appShortVersion ? appShortVersion : appVersion) cStringUsingEncoding:NSUTF8StringEncoding], [minSysVersion cStringUsingEncoding:NSUTF8StringEncoding], [SystemVersion cStringUsingEncoding:NSUTF8StringEncoding], (i == [ipaFiles count] - 1) || forceInstall ? "\n" : "\n\n");
 
                if (!removeAllContentsUnderPath(workPath)) {
                    if (quietInstall < 2)
                        printf("Failed to clean caches.\n");
                }
 
                continue;
            }
        }
 
        //Chekc capabilities
        if (requiredCapabilities) {
            BOOL isCapable = YES;
            //requiredCapabilities is NSArray, contains only strings
            if ([requiredCapabilities isKindOfClass:[NSArray class]]) {
                NSMutableArray *newCapabilities = [NSMutableArray arrayWithCapacity:0];
 
                for (unsigned int j=0; j<[(NSArray *)requiredCapabilities count]; j++) {
                    NSString *capability = [(NSArray *)requiredCapabilities objectAtIndex:j];
                    if ([[UIDevice currentDevice] supportsCapability:capability])
                        [newCapabilities addObject:capability];
                    else {
                        isCapable = NO;
                        if (forceInstall) {
                            if (quietInstall == 0)
                                printf("Your device does not support %s capability.\n", [capability cStringUsingEncoding:NSUTF8StringEncoding]);
 
                            shouldUpdateInfoPlist = YES;
                        } else {
                            if (quietInstall < 2)
                                printf("Your device does not support %s capability.\n", [capability cStringUsingEncoding:NSUTF8StringEncoding]);
                        }
                    }
                }
 
                if (!isCapable) {
                    if (forceInstall)
                        [infoDict setObject:[newCapabilities sortedArrayUsingSelector:@selector(compare:)] forKey:@"UIRequiredDeviceCapabilities"];
                    else {
                        if (!removeAllContentsUnderPath(workPath)) {
                            if (quietInstall < 2)
                                printf("Failed to clean caches.\n");
                        }
 
                        if (i != [ipaFiles count] - 1) //Not the last output
                            printf("\n");
 
                        continue;
                    }
                }
            } else if ([requiredCapabilities isKindOfClass:[NSDictionary class]]) {
                //requiredCapabilities is NSDictionary, contains only key-object pairs
                NSMutableDictionary *newCapabilities = [NSMutableDictionary dictionaryWithCapacity:0];
 
                for (NSString *capabilityKey in [(NSDictionary *)requiredCapabilities allKeys]) {
                    BOOL capabilityValue = [[(NSDictionary *)requiredCapabilities objectForKey:capabilityKey] boolValue];
 
                    //Only boolean value
                    if (capabilityValue == [[UIDevice currentDevice] supportsCapability:capabilityKey])
                        [newCapabilities setObject:[NSNumber numberWithBool:!capabilityValue] forKey:capabilityKey];
                    else {
                        isCapable = NO;
                        if (forceInstall) {
                            if (quietInstall == 0) {
                                if (capabilityValue) //Device does not support
                                    printf("Your device does not support %s capability.\n", [capabilityKey cStringUsingEncoding:NSUTF8StringEncoding]);
                                else //Device support but IPA requires to be false
                                    printf("Your device conflicts with %s capability.\n", [capabilityKey cStringUsingEncoding:NSUTF8StringEncoding]);
                            }
 
                            shouldUpdateInfoPlist = YES;
                        } else {
                            if (quietInstall < 2) {
                                if (capabilityValue) //Device does not support
                                    printf("Your device does not support %s capability.\n", [capabilityKey cStringUsingEncoding:NSUTF8StringEncoding]);
                                else //Device support but IPA requires to be false
                                    printf("Your device conflicts with %s capability.\n", [capabilityKey cStringUsingEncoding:NSUTF8StringEncoding]);
                            }
                        }
                    }
                }
                if (!isCapable) {
                    if (forceInstall)
                        [infoDict setObject:newCapabilities forKey:@"UIRequiredDeviceCapabilities"];
                    else {
                        if (!removeAllContentsUnderPath(workPath)) {
                            if (quietInstall < 2)
                                printf("Failed to clean caches.\n");
                        }
 
                        if (i != [ipaFiles count] - 1) //Not the last output
                            printf("\n");
 
                        continue;
                    }
                }
            }
        }
 
        if (shouldUpdateInfoPlist && ![infoDict writeToFile:pathInfoPlist atomically:YES]) {
            if (quietInstall < 2)
                printf("Failed to use force installation mode, %s (v%s) will not be installed.%s", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding], [(appShortVersion ? appShortVersion : appVersion) cStringUsingEncoding:NSUTF8StringEncoding], (i == [ipaFiles count] - 1) ? "\n" : "\n\n");
            continue;
        }
 
        //Copy file to install
        if ([fileMgr fileExistsAtPath:installPath]) {
            if (![fileMgr removeItemAtPath:installPath error:nil]) {
                if (quietInstall < 2)
                    printf("Failed to delete %s.\n", [installPath cStringUsingEncoding:NSUTF8StringEncoding]);
 
                if (![fileMgr removeItemAtPath:workPath error:nil]) {
                    if (quietInstall < 2)
                        printf("Failed to clean caches.\n");
                }
 
                [pool release];
                return IPA_FAILED;
            }
        }
 
        if (![fileMgr copyItemAtPath:ipa toPath:installPath error:nil]) {
            if (quietInstall < 2)
                printf("Failed to create temporaty files.\n");
 
            if (![fileMgr removeItemAtPath:workPath error:nil] && quietInstall < 2)
                printf("Failed to clean caches.\n");
 
            [pool release];
            return IPA_FAILED;
        }
 
        //Modify ipa to force install
        if (shouldUpdateInfoPlist) {
            BOOL shouldContinue = NO;
            ZipArchive *tmpArchive = [[ZipArchive alloc] init];
            // APPEND_STATUS_ADDINZIP = 2
            if ([tmpArchive openZipFile2:installPath withZipModel:APPEND_STATUS_ADDINZIP] && ![tmpArchive addFileToZip:pathInfoPlist newname:infoPath]) {
                if (quietInstall < 2)
                    printf("Failed to use force installation mode, %s (v%s) will not be installed.%s", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding], [(appShortVersion ? appShortVersion : appVersion) cStringUsingEncoding:NSUTF8StringEncoding], (i == [ipaFiles count] - 1) ? "\n" : "\n\n");
 
                //Delete copied file
                [fileMgr removeItemAtPath:installPath error:nil];
 
                shouldContinue = YES;
            }
            [tmpArchive release];
 
            //Remove extracted Info.plist
            [fileMgr removeItemAtPath:pathInfoPlist error:nil];
 
            if (shouldContinue) {
                if (!removeAllContentsUnderPath(workPath)) {
                    if (quietInstall < 2)
                        printf("Failed to clean caches.\n");
                }
 
                continue;
            }
        }
 
        if (quietInstall == 0)
            printf("%snstalling %s (v%s)...\n", shouldUpdateInfoPlist ? "Force i" : "I", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding], [(appShortVersion ? appShortVersion : appVersion) cStringUsingEncoding:NSUTF8StringEncoding]);
 
        //Set permission before installation
        setPermissionsForPath(workPath);
 
        int ret = installApp(installPath, appIdentifier);
 
        if (ret == 0) {
            //Get installation path
            NSDictionary *installedAppDict = getInstalledAppInfo(appIdentifier);
 
            if (installedAppDict) {
                NSString *installedVerion = [installedAppDict objectForKey:@"VERSION"];
                NSString *installedShortVersion = [installedAppDict objectForKey:@"SHORT_VERSION"];
                NSString *installedAppLocation = [installedAppDict objectForKey:@"BUNDLE_PATH"];
                NSString *installedDataLocation = [installedAppDict objectForKey:@"DATA_PATH"];
                NSString *appDirPath = [installedAppDict objectForKey:@"APP_PATH"];
 
                BOOL appInstalled = YES;
                if (appInstalled && versionCompare(installedVerion, appVersion) != 0)
                    appInstalled = NO;
                if (appInstalled && versionCompare(installedShortVersion, appShortVersion) != 0)
                    appInstalled = NO;
 
                if (appInstalled) {
                    //Recover the original Info.plist in force installation
                    if (shouldUpdateInfoPlist) {
                        NSString *pathInstalledInfoPlist = [NSString stringWithFormat:@"%@/%@/Info.plist", installedAppLocation, [[infoPath pathComponents] objectAtIndex:1]];
                        BOOL isDirectory;
                        if ([fileMgr fileExistsAtPath:pathInstalledInfoPlist isDirectory:&isDirectory]) {
                            if (!isDirectory) {
                                if ([fileMgr removeItemAtPath:pathInstalledInfoPlist error:nil]) {
                                    if ([fileMgr moveItemAtPath:pathOriginalInfoPlist toPath:pathInstalledInfoPlist error:nil]) {
                                        if ([fileMgr fileExistsAtPath:pathOriginalInfoPlist])
                                            [fileMgr removeItemAtPath:pathOriginalInfoPlist error:nil];
                                    }
                                }
                            }
                        }
                    }
 
                    successfulInstalls++;
                    if (quietInstall == 0)
                        printf("%snstalled %s (v%s) successfully%s.\n", shouldUpdateInfoPlist ? "Force i" : "I", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding], [(appShortVersion ? appShortVersion : appVersion) cStringUsingEncoding:NSUTF8StringEncoding], shouldUpdateInfoPlist ? ", but it may not work properly" : "");
 
                    BOOL tempEnableClean = NO;
                    if (!cleanInstall && hasContainer && !notRestore) {
                        tempEnableClean = YES;
                        cleanInstall = YES;
                    }
 
                    //Clear documents, etc.
                    if (appAlreadyInstalled && cleanInstall) {
                        if (quietInstall == 0)
                            printf("Cleaning old contents of %s...\n", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding]);
 
                        BOOL allContentsCleaned = YES;
 
                        NSArray *dataContents = [fileMgr contentsOfDirectoryAtPath:installedDataLocation error:nil];
                        for (NSString *file in dataContents) {
                            if ([file hasSuffix:@".app"] ||
                                [file isEqualToString:@".com.apple.mobile_container_manager.metadata.plist"] ||
                                [file isEqualToString:@".com.apple.mobileinstallation.placeholder"] ||
                                [file isEqualToString:@"iTunesArtwork"] ||
                                [file isEqualToString:@"iTunesMetadata.plist"])
                                continue;
 
                            if ([file isEqualToString:@"Library"]){
                                NSString *dirLibrary = [installedDataLocation stringByAppendingPathComponent:@"Library"];
                                NSString *dirPreferences = [dirLibrary stringByAppendingPathComponent:@"Preferences"];
                                NSString *dirCaches = [dirLibrary stringByAppendingPathComponent:@"Caches"];
 
                                NSArray *dirContents = [fileMgr contentsOfDirectoryAtPath:dirLibrary error:nil];
                                for (int unsigned j=0; j<[dirContents count]; j++) {
                                    NSString *fileName = [dirContents objectAtIndex:j];
                                    if ([fileName isEqualToString:@"Preferences"]) {
                                        NSArray *preferencesContents = [fileMgr contentsOfDirectoryAtPath:dirPreferences error:nil];
                                        for (unsigned int k=0; k<[preferencesContents count]; k++) {
                                            NSString *preferenceFile = [preferencesContents objectAtIndex:k];
                                            if (![preferenceFile isEqualToString:@".GlobalPreferences.plist"] && ![preferenceFile isEqualToString:@"com.apple.PeoplePicker.plist"]) {
                                                if (![fileMgr removeItemAtPath:[dirPreferences stringByAppendingPathComponent:preferenceFile] error:nil])
                                                    allContentsCleaned = NO;
                                            }
                                        }
                                    } else if ([fileName isEqualToString:@"Caches"]) {
                                        NSArray *cachesContents = [fileMgr contentsOfDirectoryAtPath:dirCaches error:nil];
                                        for (unsigned int k=0; k<[cachesContents count]; k++) {
                                            if (![fileMgr removeItemAtPath:[dirCaches stringByAppendingPathComponent:[cachesContents objectAtIndex:k]] error:nil])
                                                allContentsCleaned = NO;
                                        }
                                    } else {
                                        if (![fileMgr removeItemAtPath:[dirLibrary stringByAppendingPathComponent:fileName] error:nil])
                                            allContentsCleaned = NO;
                                    }
                                }
                            } else {
                                NSString *sourcePath = [installedDataLocation stringByAppendingPathComponent:file];
                                BOOL isDir;
                                if ([fileMgr fileExistsAtPath:sourcePath isDirectory:&isDir] && isDir) {
                                    NSArray *dirContents = [fileMgr contentsOfDirectoryAtPath:sourcePath error:nil];
                                    for (int unsigned j=0; j<[dirContents count]; j++) {
                                        if (![fileMgr removeItemAtPath:[sourcePath stringByAppendingPathComponent:[dirContents objectAtIndex:j]] error:nil])
                                            allContentsCleaned = NO;
                                    }
                                } else {
                                    if (![fileMgr removeItemAtPath:sourcePath error:nil])
                                        allContentsCleaned = NO;
                                }
                            }
                        }
 
                        if (!allContentsCleaned) {
                            if (quietInstall < 2)
                                printf("Failed to clean old contents of %s.\n", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding]);
                        }
                    }
 
                    if (tempEnableClean)
                        cleanInstall = NO;
 
                    //Recover documents
                    if (!cleanInstall && hasContainer && !notRestore) {
                        //The tmp ipa file is already deleted.
                        ipaArchive = [[ZipArchive alloc] init];
                        if ([ipaArchive unzipOpenFile:[ipaFiles objectAtIndex:i]]) {
                            if ([ipaArchive unzipFileWithName:@"Container" toPath:[workPath stringByAppendingPathComponent:@"Container"] overwrite:YES]) {
                                NSString *containerPath = [workPath stringByAppendingPathComponent:@"Container"];
 
                                NSArray *containerContents = [fileMgr contentsOfDirectoryAtPath:containerPath error:nil];
                                if ([containerContents count] > 0) {
                                    BOOL allSuccessfull = YES;
                                    for (unsigned int j=0; j<[containerContents count]; j++) {
                                        NSString *dirName = [containerContents objectAtIndex:j];
                                        if ([dirName isEqualToString:@"Library"]) {
                                            NSString *containerLibraryPath = [containerPath stringByAppendingPathComponent:dirName];
                                            NSArray *containerLibraryContents = [fileMgr contentsOfDirectoryAtPath:containerLibraryPath error:nil];
                                            for (unsigned int k=0; k<[containerLibraryContents count]; k++) {
                                                NSString *dirLibraryName = [containerLibraryContents objectAtIndex:k];
                                                if ([dirLibraryName isEqualToString:@"Caches"]) {
                                                    NSString *dirCachePath = [containerLibraryPath stringByAppendingPathComponent:dirLibraryName];
                                                    NSArray *containerCachesContents = [fileMgr contentsOfDirectoryAtPath:dirCachePath error:nil];
                                                    for (unsigned int m=0; m<[containerCachesContents count]; m++) {
                                                        if (![fileMgr moveItemAtPath:[dirCachePath stringByAppendingPathComponent:[containerCachesContents objectAtIndex:m]] toPath:[[[installedDataLocation stringByAppendingPathComponent:dirName] stringByAppendingPathComponent:dirLibraryName] stringByAppendingPathComponent:[containerCachesContents objectAtIndex:m]] error:nil])
                                                            allSuccessfull = NO;
                                                    }
                                                } else if ([dirLibraryName isEqualToString:@"Preferences"]) {
                                                    NSString *dirPreferencesPath = [containerLibraryPath stringByAppendingPathComponent:dirLibraryName];
                                                    NSArray *containerPreferencesContents = [fileMgr contentsOfDirectoryAtPath:dirPreferencesPath error:nil];
                                                    for (unsigned int m=0; m<[containerPreferencesContents count]; m++) {
                                                        NSString *preferencesFileName = [containerPreferencesContents objectAtIndex:m];
                                                        if (![preferencesFileName isEqualToString:@".GlobalPreferences.plist"] && ![preferencesFileName isEqualToString:@"com.apple.PeoplePicker.plist"]) {
                                                            if (![fileMgr moveItemAtPath:[dirPreferencesPath stringByAppendingPathComponent:preferencesFileName] toPath:[[[installedDataLocation stringByAppendingPathComponent:dirName] stringByAppendingPathComponent:dirLibraryName] stringByAppendingPathComponent:preferencesFileName] error:nil])
                                                                allSuccessfull = NO;
                                                        }
                                                    }
                                                } else {
                                                    if (![fileMgr moveItemAtPath:[containerLibraryPath stringByAppendingPathComponent:dirLibraryName] toPath:[[installedDataLocation stringByAppendingPathComponent:dirName] stringByAppendingPathComponent:dirLibraryName] error:nil])
                                                        allSuccessfull = NO;
                                                }
                                            }
                                        } else {
                                            NSString *containerSourcePath = [containerPath stringByAppendingPathComponent:dirName];
                                            NSString *destPath = [installedDataLocation stringByAppendingPathComponent:dirName];
                                            if ([fileMgr fileExistsAtPath:destPath]) {
                                                if ([fileMgr removeItemAtPath:destPath error:nil]) {
                                                    if (![fileMgr moveItemAtPath:containerSourcePath toPath:destPath error:nil])
                                                        allSuccessfull = NO;
                                                } else
                                                    allSuccessfull = NO;
                                            } else {
                                                if (![fileMgr moveItemAtPath:containerSourcePath toPath:destPath error:nil])
                                                    allSuccessfull = NO;
                                            }
                                        }
                                    }
                                    if (!allSuccessfull) {
                                        if (quietInstall < 2)
                                            printf("Cannot restore all saved documents and other resources.\n");
                                    }
                                }
                            }
                            [ipaArchive unzipCloseFile];
                        }
                        [ipaArchive release];
                    }
 
                    //Remove metadata
                    BOOL isDirectory;
                    if (removeMetadata && [fileMgr fileExistsAtPath:[installedAppLocation stringByAppendingPathComponent:@"iTunesMetadata.plist"] isDirectory:&isDirectory]) {
                        if (!isDirectory) {
                            if (quietInstall == 0)
                                printf("Removing iTunesMetadata.plist for %s...\n", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding]);
                            if (![fileMgr removeItemAtPath:[installedAppLocation stringByAppendingPathComponent:@"iTunesMetadata.plist"] error:nil]) {
                                if (quietInstall < 2)
                                    printf("Failed to remove %s.\n", [[installedAppLocation stringByAppendingPathComponent:@"iTunesMetadata.plist"] cStringUsingEncoding:NSUTF8StringEncoding]);
                            }
                        }
                    }
 
                    //Set overall permission
                    if (kCFCoreFoundationVersionNumber < 793.00)
                        setPermissionsForPath(installedAppLocation);
                    else
                        setPermissionsForPath(installedDataLocation); //Restore data directory's user/group for writing
                    setExecutables(appDirPath);
                } else {
                    if (quietInstall < 2)
                        printf("Failed to install %s (v%s).\n", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding], [(appShortVersion ? appShortVersion : appVersion) cStringUsingEncoding:NSUTF8StringEncoding]);
                }
            } else {
                if (quietInstall < 2)
                    printf("Failed to install %s (v%s).\n", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding], [(appShortVersion ? appShortVersion : appVersion) cStringUsingEncoding:NSUTF8StringEncoding]);
            }
        } else {
            if (quietInstall < 2)
                printf("Failed to install %s (v%s).\n", [appDisplayName cStringUsingEncoding:NSUTF8StringEncoding], [(appShortVersion ? appShortVersion : appVersion) cStringUsingEncoding:NSUTF8StringEncoding]);
        }
 
        //Delete tmp ipa file
        if (!removeAllContentsUnderPath(workPath)) {
            if (quietInstall < 2)
                printf("Failed to delete %s.%s", [installPath cStringUsingEncoding:NSUTF8StringEncoding], (i == [ipaFiles count] - 1) ? "\n" : "\n\n");
 
            [pool release];
            return IPA_FAILED;
        }
 
        //Delete original ipa
        if (deleteFile && [fileMgr fileExistsAtPath:ipa]) {
            if (![fileMgr removeItemAtPath:ipa error:nil]) {
                if (quietInstall < 2)
                    printf("Failed to delete %s.\n", [ipa cStringUsingEncoding:NSUTF8StringEncoding]);
            }
        }
 
        if (quietInstall == 0 && i < [ipaFiles count]-1)
            printf("\n");
    }
 
    if (!removeAllContentsUnderPath(workPath)) {
        if (quietInstall < 2)
            printf("Failed to clean caches.\n");
    }
 
    [pool release];
 
    return successfulInstalls;
}

https://github.com/autopear/ipainstaller

中的theos工程经过make之后,需要手动ldid签名,之后打包deb才能正常工作

签名格式:

 ldid -Ssign.plist XXXXX 

  

posted @   兜兜有糖的博客  阅读(3337)  评论(4编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示