Rework SDK default directory.
[src/xds/xds-server.git] / scripts / sdks / agl / db-dump
1 #!/usr/bin/python
2 #
3 #/**************************************************************************
4 # * Copyright 2017-2018 IoT.bzh
5 # *
6 # * author: Romain Forlot <romain.forlot@iot.bzh>
7 # *
8 # * Licensed under the Apache License, Version 2.0 (the "License");
9 # * you may not use this file except in compliance with the License.
10 # * You may obtain a copy of the License at
11 # *
12 # *     http://www.apache.org/licenses/LICENSE-2.0
13 # *
14 # * Unless required by applicable law or agreed to in writing, software
15 # * distributed under the License is distributed on an "AS IS" BASIS,
16 # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 # * See the License for the specific language governing permissions and
18 # * limitations under the License.
19 # **************************************************************************/
20
21 import os
22 import json
23 import logging
24 import inspect
25 import fnmatch
26 import argparse
27 import subprocess
28
29 PARSER = argparse.ArgumentParser(
30     description='Lists available and installed SDKs')
31 PARSER.add_argument('-debug', dest='debug', action='store_true',
32                     help='Output debug log messages')
33
34 ARGS = PARSER.parse_args()
35
36 if ARGS.debug:
37     logging.basicConfig(level=logging.DEBUG,
38                         format='%(asctime)s:%(levelname)s: %(message)s')
39 else:
40     logging.basicConfig(level=logging.INFO,
41                         format='%(asctime)s:%(levelname)s: %(message)s')
42
43 SCRIPT_PATH = os.path.dirname(os.path.abspath(
44     inspect.getfile(inspect.currentframe())))
45
46 ENV = subprocess.check_output(
47     [os.path.join(SCRIPT_PATH, './_env-init.sh'), '-print']).splitlines()
48
49 for elt in ENV:
50     k, v = elt.split('=', 1)
51     if k == 'SDK_ROOT_DIR':
52         SDK_ROOT_DIR = v.rstrip('/')
53     elif k == 'SDK_ENV_SETUP_FILENAME':
54         SDK_ENV_SETUP_FILENAME = v
55
56 if SDK_ROOT_DIR is None:
57     logging.error('No SDK_ROOT_DIR environment variable found.')
58     exit(1)
59 elif SDK_ENV_SETUP_FILENAME is None:
60     SDK_ENV_SETUP_FILENAME = 'environment-setup*'
61
62 # Get list of available SDKs
63 SDK_DB_FILEPATH = os.path.join(SDK_ROOT_DIR, "sdks_latest.json")
64
65 if not os.path.exists(SDK_DB_FILEPATH):
66     DB_UPDATE_FILEPATH = os.path.join(SCRIPT_PATH, 'db-update')
67     os.system(DB_UPDATE_FILEPATH + " " + SDK_DB_FILEPATH)
68
69 SDK_DB_JSON = json.load(open(SDK_DB_FILEPATH, 'r'))
70
71 for one_sdk in SDK_DB_JSON:
72     one_sdk['status'] = 'Not Installed'
73
74 INSTALLED_SDK = []
75 for root, dirs, files in os.walk(SDK_ROOT_DIR):
76     depth = root[len(SDK_ROOT_DIR) + len(os.path.sep):].count(os.path.sep)
77     # Limit the walking depth of processed directories
78     if depth >= 4:
79         dirs[:] = []
80     # Only process SDK dir matching profile/version/arch or
81     # profile/version/arch/tag
82     elif depth != 2 and depth != 3:
83         continue
84     EF, VF = '', ''
85     for one_file in files:
86         if fnmatch.fnmatch(one_file, SDK_ENV_SETUP_FILENAME):
87             EF = os.path.join(root, one_file)
88         if fnmatch.fnmatch(one_file, 'version-*'):
89             VF = os.path.join(root, one_file)
90     if EF != '' and VF != '':
91         logging.debug('Adding installed SDK ' + root)
92         INSTALLED_SDK.append({'ENV_FILE': EF, 'VERSION_FILE': VF})
93     elif (EF == '' and VF != '') or (EF != '' and VF == ''):
94         logging.debug(
95             'WARNING SDK ignored : root=%s, EnvFile=%s, VersFile=%s', root, EF, VF)
96
97 for one_sdk in INSTALLED_SDK:
98     logging.debug("Processing %s", one_sdk['ENV_FILE'])
99     envFile = one_sdk['ENV_FILE'].split(SDK_ROOT_DIR+'/')[1]
100     PROFILE = envFile.split('/')[0]
101     VERSION = envFile.split('/')[1]
102     ARCH = envFile.split('/')[2]
103     DIR = os.path.dirname(one_sdk['ENV_FILE'])
104     if PROFILE == '' or VERSION == '' or ARCH == '' or DIR == '':
105         logging.debug('Path not compliant, skipping')
106         continue
107
108     SDK_DATE = ''
109     for line in open(one_sdk['VERSION_FILE']).readlines():
110         if line.startswith('Timestamp'):
111             D = line.split(':')[1]
112             if D:
113                 D = D.strip()
114                 SDK_DATE = '{}-{}-{} {}:{}'.format(
115                     D[0:4], D[4:6], D[6:8], D[8:10], D[10:12])
116                 logging.debug('Found date: %s', SDK_DATE)
117
118     found = False
119     for sdk in SDK_DB_JSON:
120         if sdk['profile'] == PROFILE and sdk['version'] == VERSION and sdk['arch'] == ARCH:
121             if sdk['status'] == 'Installed':
122                 continue
123             found = True
124             sdk['status'] = 'Installed'
125             sdk['date'] = SDK_DATE
126             sdk['setupFile'] = one_sdk['ENV_FILE']
127             sdk['path'] = DIR
128             break
129
130     if not found:
131         logging.debug('Not found in database, add: ' +
132                       PROFILE + '-' + ARCH + '-' + VERSION)
133         NEW_SDK = {
134             'name': PROFILE + '-' + ARCH + '-' + VERSION,
135             'description': 'AGL SDK ' + ARCH + ' (version ' + VERSION + ')',
136             'profile': PROFILE,
137             'version': VERSION,
138             'arch': ARCH,
139             'path': DIR,
140             'url': "",
141             'status': "Installed",
142             'date': SDK_DATE,
143             'size': "",
144             'md5sum': "",
145             'setupFile': one_sdk['ENV_FILE']
146         }
147         SDK_DB_JSON.append(NEW_SDK)
148
149 print(json.dumps(SDK_DB_JSON))