Commit 6048c372 authored by Amadeu Andrade Barbosa Junior's avatar Amadeu Andrade Barbosa Junior
Browse files

Conforme issue OPENBUS-95 do JIRA, criei a primeira versão do instalador:

 - descritores de pacotes (.desc) agora podem informar arquivos de 
 configuração
 - instalador faz perguntas mediante um template de configuração também 
 informado no descritor do pacote
 - instalador permite que o desenvolvedor/empacotador tenha uma função especial
 para configurar o pacote após o usuário ter respondido as perguntas definidas
 no template de configuração
 - instalador permite que o administrador informe um arquivo com configurações
 antigas (da última instalação) e assim a instalação torna-se mais automática e 
 menos interativa

CORREÇÕES:
  build/tecmake.lua : incluir "/" na string do build_dir, pois é concatenada com 
  outros caminhos de diretórios ao longo da execução.
  
  makepack.lua : tornando-o mais compatível com diferentes versões de Unix, mas
  ainda depende de um 'tar' que aceite a opção '--exclude'.

ADICIONADOS:
  * installer.lua : Assume que um pacote Openbus válido precisa ter um arquivo
  de metadados chamado 'metadata.tar.gz'. Nesse estarão os arquivos .files, 
  .links e .template. Esse novo tipo de arquivo .template reflete um arquivo
  modelo de configuração em que o EMPACOTADOR planeja quais dados o usuário deve
  preencher durante a instalação e também pode ter um função "configure_action" 
  que será chamada pelo instalador na etapa de configuração do pacote.
  Atualmente apenas o 'openbus-core' tem configurações e a ação é gerar os
  arquivos core/conf/*Configuration.lua da raiz do Openbus.

  * templates/openbus.lua : criando a função de configure_action que
  até o último commit era responsabilidade do instalador

A grande vantagem de permitir um template de configuração é que para cada pacote
pode-se ter uma semântica própria de configuração. A idéia é que o administrador
pode pegar o arquivo de saída (/tmp/lastest.answers) do instalador, e reusar 
para a próxima instalação como respostas padrões às perguntas do template.
Se houverem novas perguntas no template de um pacote mais novo, então garantimos
que elas serão feitas. 

Caso hajam novas propriedades ele será avisado e poderá
definir (via perguntas ou cancelando e atualizando seu arquivo).

MELHORIAS:
  * config.lua : criação de uma função 'changePlatform' para permitir mudança de
  variáveis específicas à plataforma, o que é importante para o script de
  'makepack'
  
  * packages.desc : adição de duas novas tabelas específicas para arquivos de
  configuração
    * conf_files : indica quais são os arquivos de configuração, para permitir
  na instalação não sobreescreer os antigos, haverá assim um pacote separado
  chamado "<seupacote>-conf" semelhante a "<seupacote>-dev"
    * conf_template : indica qual arquivo de template, um template contém uma
  tabela 'messages' com as configurações que serão SOLICITADAS interativamente
  ao usuário, nesse template usa-se tipos de campos especiais que podem ser
  definidos dentro do próprio arquivo para manipular tipos complexos como
  hashmaps especializados (ex: ldapHosts= {name ="hostname", port="portnumber"})
  TODO: conf_template poderia ser uma tabela com o conteúdo que hoje está nesse
  arquivo externo de template da configuração. Também pode conter uma função
  'configure_action' que será carregada durante a etapa de configuração.

  * platforms.lua : adicionei cmd.ls, cmd.mkdir e cmd.rm
  
  * build/copy.lua : adição do tratamento dos campos conf_tempalte e conf_files
  
  * util.lua: adicionei uma serialização de tabelas simples existente no guia
  de programação de Lua (lua.org/pil). As tabelas podem ser nomeadas, assim no
  arquivo haverá "nome = { --[[conteudo da tabela]]-- }".
  Adicionei também a função parse_args para simplificar as tarefas em cada 
  script de compile, makepack e installer.

  * profiles/* : agora incluem o novo pacote 'openbus-core-conf'

  * compile.lua, makepack.lua : refatorando para uniformizar a interação com a
  linha de comando, através de util.parse_args.

git-svn-id: https://subversion.tecgraf.puc-rio.br/engdist/openbus/trunk@85885 ae0415b3-e90b-0410-900d-d0be9363c56b
parent e534a517
......@@ -11,10 +11,10 @@ local myplat = platforms[TEC_SYSNAME]
module("tools.build.autotools",package.seeall)
-- Ensure tempdirs for bogus ./configure
os.execute("mkdir -p ".. TMPDIR)
os.execute("mkdir -p ".. TMPDIR .."/bin")
os.execute("mkdir -p ".. TMPDIR .."/lib")
os.execute("mkdir -p ".. TMPDIR .."/include")
os.execute(myplat.cmd.mkdir .. TMPDIR)
os.execute(myplat.cmd.mkdir .. TMPDIR .."/bin")
os.execute(myplat.cmd.mkdir .. TMPDIR .."/lib")
os.execute(myplat.cmd.mkdir .. TMPDIR .."/include")
-- Build dependencies check (originaly) to basesoft packages
function check_external_deps(pkgtable)
......@@ -73,7 +73,7 @@ function run(t,arguments)
-- assert ensure that we could continue
assert(ret == 0,"ERROR compiling the software ".. t.name .."")
-- re-using copy method to parse install_files, dev_files
-- re-using copy method to parse install_files, conf_files, dev_files
copy.run(t,arguments,build_dir)
break
end
......
......@@ -27,6 +27,20 @@ function run(t,arguments,build_dir)
util.install(t.name, build_dir .. orig, dest)
end
end
-- copying files related to configuration with '-conf' suffix
if t.conf_files then
for orig, dest in pairs(t.conf_files) do
-- if absolute path we assume that you know where get the files
if orig:match("^/") then build_dir = "" end
util.install(t.name.."-conf", build_dir.. orig, dest)
end
end
-- temp behaviour, future: each package as a <name>.desc and <name>.template
-- important for configuration procedure in installation time
if t.conf_template then
local content = assert(io.open(t.conf_template,"r")):read("*a")
assert(io.open(PKGDIR.."/"..t.name..".template", "w")):write(content)
end
-- copying files to special packages with '-dev' suffix
if t.dev_files then
for orig, dest in pairs(t.dev_files) do
......
......@@ -13,6 +13,8 @@ module("tools.build.tecmake", package.seeall)
function run(t, arguments)
print(" [info] Compiling package via tecmake: ".. t.name)
local build_dir = t.build.src
if not build_dir:match("/$") then build_dir = build_dir.."/" end
for _, mf in ipairs(t.build.mf) do
-- compiling all targets
local build_cmd = "cd ".. build_dir .. "; ".. "tecmake MF=".. mf
......@@ -36,6 +38,6 @@ function run(t, arguments)
util.install(t.name.."-dev", build_dir .. "../include/*", INSTALL.INC .. t.name )
end
-- re-using copy method to parse install_files, dev_files
-- re-using copy method to parse install_files, conf_files, dev_files
copy.run(t,arguments,build_dir)
end
......@@ -11,15 +11,36 @@ local platforms = require "tools.platforms"
local myplat = platforms[TEC_SYSNAME]
local default_assert = assert
-- Parses package description and delegates to tools.build.<method>.run
function parseDescriptions(desc, arguments)
for _, t in ipairs(desc) do
print "----------------------------------------------------------------------"
-- hack when no build is provided, to _always_ copy install_files , dev_files
if not t.build then
t.build = { type = "copy" }
end
assert(t.build.type, "ERROR: build.type is missing for package: "..t.name)
-- loading specific build methods
ok, build_type = pcall(require, "tools.build." .. t.build.type)
assert(ok and type(build_type) == "table","ERROR: failed initializing "..
"build back-end for build type: '".. t.build.type ..
"' for package: ".. t.name)
-- starting specific build methods
build_type.run(t,arguments)
print " [info] Done!"
print "----------------------------------------------------------------------"
end
end
--------------------------------------------------------------------------------
-- Parsing arguments, filtering descriptions and reaching basic requests -------
-- Main code -------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Parsing arguments
assert(arg,"Table arg missing! This program should be loaded from console.")
local arguments = {}
local patt="%-?%-?(%w+)(=?)(.*)"
local usage_msg=[[ Usage: ]]..arg[0]..[[ OPTIONS
Valid OPTIONS:
local arguments = util.parse_args(arg,[[
--help : show this help
--verbose : turn ON the VERBOSE mode (show the system commands)
--basesoft=filename : use the 'filename' as input for basic
......@@ -33,24 +54,14 @@ local usage_msg=[[ Usage: ]]..arg[0]..[[ OPTIONS
already = to debug or devel purpose)
--list : list all package names from description files. When
'--select' is used, it'll confirm the selection.
--select="pkg1 pkg2 ..." : choose which packages to compile and install ]]
for i,param in ipairs(arg) do
local opt,_,value = string.match(param,patt)
if opt == "h" or opt == "help" then
print(usage_msg)
os.exit(0)
end
if opt and value then
if opt == "select" then
-- selecting packages to build with multiple '--select' support
if not arguments[opt] then arguments[opt] = {} end
for _,pkg in ipairs({value:split("[^%s]+")}) do
arguments[opt][pkg] = pkg
end
else
arguments[opt] = value
end
--select="pkg1 pkg2 ..." : choose which packages to compile and install ]])
if arguments.select then
local value = arguments.select
-- selecting packages to build with multiple '--select' support
arguments.select = {}
for _,pkg in ipairs({value:split("[^%s]+")}) do
arguments.select[pkg] = pkg
end
end
......@@ -64,8 +75,8 @@ assert(loadfile(arguments["packages"] or DEPLOYDIR .."/packages.desc"))()
-- Filtering the descriptions tables with '--select' arguments
-- preparing the tables to provide t[pkg_name] fields
function rehashByName(mytable)
-- REMEMBER: loop.ordered.set is better but insert loop dependency
local function rehashByName(mytable)
-- REMEMBER: loop.ordered.set is better but insert 'loop' module dependency
for i,t in ipairs(mytable) do
mytable[t.name] = t
end
......@@ -105,60 +116,29 @@ if arguments["list"] then
os.exit(0)
end
--------------------------------------------------------------------------------
-- Useful functions (overloading, install and link) ----------------------------
--------------------------------------------------------------------------------
-- Setting verbose level if requested
if arguments["verbose"] or arguments["v"] then
util.verbose(1)
end
--------------------------------------------------------------------------------
-- Main code -------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Creating the build environment to create .tar.gz (later) from it
os.execute("mkdir -p ".. INSTALL.TOP)
os.execute("mkdir -p ".. INSTALL.LIB)
os.execute("mkdir -p ".. INSTALL.BIN)
os.execute("mkdir -p ".. INSTALL.INC)
os.execute("mkdir -p ".. TMPDIR)
os.execute("mkdir -p ".. PKGDIR)
os.execute(myplat.cmd.mkdir .. INSTALL.TOP)
os.execute(myplat.cmd.mkdir .. INSTALL.LIB)
os.execute(myplat.cmd.mkdir .. INSTALL.BIN)
os.execute(myplat.cmd.mkdir .. INSTALL.INC)
os.execute(myplat.cmd.mkdir .. TMPDIR)
os.execute(myplat.cmd.mkdir .. PKGDIR)
os.execute(FETCH_CMD)
-- Cleaning the temp dir to execute install rules of autotools softwares
os.execute("rm -rf "..TMPDIR.."/*")
-- Parsing basesoft and compiling+installing on WORKDIR environment
function parseDescriptions(desc)
for _, t in ipairs(desc) do
print "----------------------------------------------------------------------"
-- hack when no build is provided, to _always_ copy install_files , dev_files
if not t.build then
t.build = { type = "copy" }
end
assert(t.build.type, "ERROR: build.type is missing for package: "..t.name)
-- loading specific build methods
ok, build_type = pcall(require, "tools.build." .. t.build.type)
assert(ok and type(build_type) == "table","ERROR: failed initializing "..
"build back-end for build type: '".. t.build.type ..
"' for package: ".. t.name)
-- starting build methods
build_type.run(t,arguments)
print " [info] Done!"
print "----------------------------------------------------------------------"
end
end
os.execute(myplat.cmd.rm .. TMPDIR .."/*")
parseDescriptions(basesoft)
parseDescriptions(packages)
-- Parsing descriptions and proceed to compile & install procedures
parseDescriptions(basesoft, arguments)
parseDescriptions(packages, arguments)
-- Cleaning environment
os.execute("rm -rf ".. TMPDIR)
os.execute(myplat.cmd.rm .. TMPDIR)
--~ I shouldn't need this!!
--~ os.execute("cd ".. INSTALL.TOP.. "; unlink lib/lib")
--~ os.execute("cd ".. INSTALL.TOP.. "; unlink include/include")
......
......@@ -5,31 +5,31 @@
-- work/install = install dir to use install_files table to copy here like:
-- cp -r -Lf lib/$TEC_UNAME/* work/install/lib/$TEC_UNAME/
assert(os.getenv("HOME"), "HOME env var not defined")
assert(os.getenv("TEC_UNAME"), "TEC_UNAME env var not defined")
assert(os.getenv("TEC_SYSNAME"), "TEC_SYSNAME env var not defined")
assert(os.getenv("HOME"), "ERROR: HOME env var not defined")
assert(os.getenv("TEC_UNAME"), "ERROR: TEC_UNAME env var not defined")
assert(os.getenv("TEC_SYSNAME"), "ERROR: TEC_SYSNAME env var not defined")
-- Tecmake compatibility variables
-- You could (in a very special case) redefine this to work with the compile.lua
TEC_UNAME = os.getenv("TEC_UNAME")
TEC_SYSNAME = os.getenv("TEC_SYSNAME")
-- Base variables to compile and install time
BASEDIR = os.getenv("HOME")
WORKDIR = BASEDIR .."/work"
PRODAPP = BASEDIR .."/prodapp"
DEPLOYDIR = BASEDIR .."/tools"
SVNDIR = WORKDIR .."/trunk"
PKGDIR = WORKDIR .."/pkgfiles/".. os.getenv("TEC_UNAME")
DEPLOYDIR = SVNDIR .."/tools"
PKGDIR = WORKDIR .."/pkgfiles/".. TEC_UNAME
INSTALL = {}
INSTALL.TOP = WORKDIR .."/install"
INSTALL.BIN = INSTALL.TOP .."/bin/".. os.getenv("TEC_UNAME") .."/"
INSTALL.LIB = INSTALL.TOP .."/libpath/".. os.getenv("TEC_UNAME") .."/"
INSTALL.BIN = INSTALL.TOP .."/bin/".. TEC_UNAME .."/"
INSTALL.LIB = INSTALL.TOP .."/libpath/".. TEC_UNAME .."/"
INSTALL.INC = INSTALL.TOP .."/incpath/"
TMPDIR = "/tmp/openbus-building_".. math.random(os.time()%100000)
-- Tecmake compatibility variables
-- You could (in a very special case) redefine this to work with the compile.lua
TEC_UNAME = os.getenv("TEC_UNAME")
TEC_SYSNAME = os.getenv("TEC_SYSNAME")
-- We must fill the work/trunk in any way
FETCH_CMD = "svn co https://subversion.tecgraf.puc-rio.br/engsoftware/openbus/trunk ".. SVNDIR .." || svn up ".. SVNDIR .."/"
......@@ -46,3 +46,15 @@ SUPPORTED_ARCH = {
"SunOS510x86",
"Darwin811x86",
}
-- Given a way to change platform specific variables.
-- Useful for the makepack script that needs create packages for many platforms
-- from a different TEC_UNAME machine.
function changePlatform(arch)
assert(PKGDIR:find(TEC_UNAME), "Variable PKGDIR isn't platform specific and you are trying changePlaform!")
assert(INSTALL.BIN:find(TEC_UNAME), "Variable INSTALL.BIN isn't platform specific and you are trying changePlaform!")
assert(INSTALL.LIB:find(TEC_UNAME), "Variable INSTALL.LIB isn't platform specific and you are trying changePlaform!")
return PKGDIR:gsub(TEC_UNAME,arch),
INSTALL.BIN:gsub(TEC_UNAME,arch),
INSTALL.LIB:gsub(TEC_UNAME,arch)
end
#!/usr/bin/env lua5.1
package.path = "?.lua;../?.lua;" .. package.path
require "tools.config"
local util = require "tools.util"
local platforms = require "tools.platforms"
local myplat = platforms[TEC_SYSNAME]
--[[
USO:
1. gera um arquivo de template da configuracao com as respostas
2. salva esse arquivo para o admin poder reusar
3. faz a configuração real no openbus (substituindo valores em core/conf/*.lua)
4. fazer a configuração a partir de um arquivo de input considerando que
o admin já tem esse 'arquivo' com as respostas
]]
CONFIG = "[ CONFIGURE ] "
INSTALL = "[ INSTALL ] "
ERROR = "[ ERROR ] "
-- Configures with user interation
function wizard(template, save)
local function parser(_,t)
-- for a complex type delegates to __call metamethod
if t.type == "list" then
t.check(t, save)
-- for a simple data asks and retrieves the answer
else
print(CONFIG,"Property name: ".. t.name)
print(CONFIG,t.msg)
io.write("> ")
local var = io.read("*l")
if t.type == "number" then
var = tonumber(var)
end
assert(type(var) == t.type, "ERROR: Invalid configuration value, should be '".. t.type.."'")
save[t.name] = var
end
end
-- call the parse for all fields in template table
table.foreach(template,parser)
end
-- Checks consistency between two configuration tables
function checker(template, cfg)
local missing = {}
for _, t in ipairs(template) do
-- if missing configuration marks in the missing table
if not cfg[t.name] then
table.insert(missing, t.name)
elseif (type(cfg[t.name]) ~= t.type) and
(type(cfg[t.name]) ~= "table" or t.type ~= "list") then
return false , "Invalid type on definition of '"..t.name.."'"
end
end
-- returns a table with the missing configuration
if #missing > 0 then
return false, "Missing some definitions", missing
end
-- it's all right and no missing
return true
end
-- Simple get to index by name
function getFieldByName(tbl, name)
for i, t in ipairs(tbl) do
if t.name == name then
return t
end
end
return nil
end
-- Launcher for the wizard that accepts an old configuration table
function launchWizard(template, cfg, reconfig_flag)
assert(type(template) == "table")
if cfg then
if reconfig_flag then
-- Force the user fill the installPath again (he could have change it)
cfg.installPath = nil
end
-- Checks the consistency of the previous configuration
local ok, errmsg, missing = checker(template.messages,cfg)
if not ok then
print(CONFIG,errmsg.. ", please complete the following properties:")
--~ print("Sua configuração está incompleta, por favor complete os items:")
local missing_msg = {}
table.foreach(missing, function(i,v)
print(" ",v)
table.insert(missing_msg,getFieldByName(template.messages,v))
end)
-- Retrieves the missing configuration from user interation
wizard(missing_msg,cfg)
else
print(CONFIG,"Thanks, your configuration is valid and was accepted!")
end
else
cfg = {}
wizard(template.messages,cfg)
end
return cfg
end
-- Loads a template table from a filename
function loadTemplate(tmplname)
assert(type(tmplname) == "string")
assert(not _G.messages and not _G.configure_action,
"ERROR: Possible BUG = Lua global environment already "..
"has _G.messages or _G.configure_action !")
assert(loadfile(tmplname),
"ERROR: Cannot import the configuration template '"..tmplname.."'")()
-- We assume that template contains a 'messages' table
assert(type(_G.messages) == "table",
"ERROR: Invalid template. Table 'messages' not found inside it.")
if _G.configure_action then
assert(type(_G.configure_action) == "function",
"ERROR: Invalid template. Function 'configure_action' not found inside it.")
end
local template = { messages = _G.messages,
configure_action = _G.configure_action,
}
_G.messages = nil
_G.configure_action = nil
return template
end
--------------------------------------------------------------------------------
-- Main code -------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Parsing arguments
local arguments = util.parse_args(arg,[[
--help : show this help
--config=filename : use 'filename' to import a previous configuration
--package=filename : package 'filename' to unpack, configure and install
--template=filename : use 'filename' as input for answers
NOTES:
If you give '--package' so the '--template' will be discard !
The '--template' is useful in manual reconfiguration only !
EXAMPLES:
]].. arg[0].. [[ --package=myOpenBus.tar.gz --config=myPrevious.answers ]])
-- Setting verbose level if requested
if arguments["verbose"] or arguments["v"] then
util.verbose(1)
end
-- Cache variables
-- ATTENTION: config as 'nil' is important if none previous conf is given
local template, config
if arguments.config then
print(CONFIG,"Input configuration file given, checking it for updates!")
local dump = assert(io.open(arguments.config,"r"),
"ERROR: Opening file"..arguments.config):read("*a")
assert(loadstring("fromconsole = "..dump), "ERROR: Invalid syntax of file")()
assert(type(fromconsole) == "table", "ERROR: Configuration should be a table")
config = fromconsole
fromconsole = nil
end
-- When no package is given assumes reconfiguration
if arguments.package then
if arguments.package:match(".*openbus.*tar.gz$") then
-- Starting the extraction of the package
print(INSTALL, "Unpacking in a temporary dir '"..TMPDIR.."'...")
assert(os.execute(myplat.cmd.mkdir .. TMPDIR) == 0)
-- Trying extract the metadata.tar.gz from package
print(INSTALL, "Extracting metadata.")
extract_cmd = "gzip -c -d "..arguments.package.." | "
extract_cmd = extract_cmd .. "tar -C ".. TMPDIR .." -x metadata.tar.gz && "
extract_cmd = extract_cmd .. "gzip -c -d ".. TMPDIR .."/metadata.tar.gz |"
extract_cmd = extract_cmd .. "tar -C ".. TMPDIR .." -x"
assert(os.execute(extract_cmd) == 0, "ERROR: '".. arguments.package ..
"' is not a valid package! Please contact the administrator!")
-- Unpacking the openbus-<<release>>_plat.tar.gz package
-- Grant to user's configure_action functions that could operate over an
-- instalation tree and at the end all files will be copied to real path
assert(os.execute("gzip -c -d "..arguments.package.." |tar -C ".. TMPDIR .." -x") == 0)
print(INSTALL, "Unpack DONE.")
print(CONFIG, "Configuring the package based on package metadata")
-- Configure main step, using all .template of this package metadata
local files = myplat.exec(myplat.cmd.ls .. TMPDIR .."/metadata/")
local nexttmpl = files:gmatch("%S+.template")
local tmplname, template
tmplname = nexttmpl()
-- For each template ...
while type(tmplname) == "string" do
-- ... parses the template
template = loadTemplate(TMPDIR.."/metadata/"..tmplname)
-- ... and launch the wizard to ask what it needs to user
config = launchWizard(template, config)
-- ... if all right then take a custom action (if exists)
if not template.configure_action then
print(CONFIG, "WARNING: Template '"..tmplname.."' don't take any action")
else
-- Takes the action planned by developer
assert(template.configure_action(config, TMPDIR, util), "ERROR: Custom action"..
" from template '"..tmplname.."' has failed!")
end
-- ... go to next template!
tmplname = nexttmpl()
end
print(CONFIG, "Configure DONE.")
-- Removing metadata files to clean the temporary tree
assert(os.execute(myplat.cmd.rm .. TMPDIR .."/metadata*") == 0)
-- Moving the temporary tree to real tree (given by user)
assert(os.execute(myplat.cmd.mkdir .. config.installPath) == 0,
"ERROR: The installation path is invalid or you cannot write there!")
assert(os.execute(myplat.cmd.install .. TMPDIR .."/* ".. config.installPath) == 0)
assert(os.execute(myplat.cmd.rm .. TMPDIR) == 0)
else
print(INSTALL,"Do nothing. You MUST provide a valid package filename "..
"'openbus-<profile>_<plat>.tar.gz' to install the OpenBus.")
print(INSTALL,"Please check --help for more instructions.")
os.exit(0)
end
else
local tmplname = arguments.template or "templates/openbus.lua"
-- Loads the template or a default one
template = loadTemplate(tmplname)
config = launchWizard(template, config, true)
-- ... if all right then take a custom action (if exists)
if not template.configure_action then
print(CONFIG, "WARNING: Template '"..tmplname.."' don't take any action")
else
-- Takes the action planned by developer
assert(template.configure_action(config, config.installPath, util), "ERROR: Custom action"..
" from template '"..tmplname.."' has failed!")
end
end
print(INSTALL,"You MUST set in your profile the sytem variable OPENBUS_HOME as:")
print("\t csh shell : setenv OPENBUS_HOME \""..config.installPath.."\"")
print("\t ksh/bash shell : export OPENBUS_HOME=\""..config.installPath.."\"")
--~ print("\t windows shell : set OPENBUS_HOME=\""..config.installPath.."\"")
-- Persisting the answers to future interactions
util.serialize_table("/tmp/lastest.answers",config)
print(INSTALL,"Saving your answers at '/tmp/lastest.answers' please backup it if you need.")
print(INSTALL,"Installation DONE!")
......@@ -5,59 +5,36 @@ package.path = "?.lua;../?.lua;" .. package.path
require "tools.config"
local util = require "tools.util"
-- Parsing arguments
assert(arg,"Table arg missing! This program should be loaded from console.")
local arguments = {}
local patt="%-?%-?(%w+)(=?)(.*)"
local usage_msg=[[ Usage: ]]..arg[0]..[[ OPTIONS
Valid OPTIONS:
--help : show this help
--verbose : turn ON the VERBOSE mode (show the system commands)
--profile=filename : use the 'filename' as input for profile with the
list of packages to packaging
--arch=tecmake_arch : specifies the arch based on tecmake way. Use 'all'
to pack all supported architectures ]]
if not (arg[1]) then print(usage_msg) ; os.exit(1) end
for i,param in ipairs(arg) do
local opt,_,value = string.match(param,patt)
if opt == "h" or opt == "help" then
print(usage_msg)
os.exit(1)
end
if opt and value then
arguments[opt] = value
end
end
-- Overloading the os.execute to dummy verbose
if arguments["verbose"] or arguments["v"] then
util.verbose(1)
end
assert(arguments["profile"],"Missing argument --profile!")
assert(arguments["arch"] or TEC_UNAME,"Missing argument --arch and not exist TEC_UNAME env!")
arguments["arch"] = arguments["arch"] or TEC_UNAME
-- Local scope
local string = require "tools.split"
local platforms = require "tools.platforms"
local myplat = platforms[TEC_SYSNAME]
-- Packs in a tarball named by profile
function pack(arch,profile)
-- Re-setting variables with arch values
PKGDIR = WORKDIR .."/pkgfiles/".. arch
INSTALL.BIN = INSTALL.TOP .."/bin/".. arch .."/"
INSTALL.LIB = INSTALL.TOP .."/libpath/".. arch .."/"
-- Overwriting some global variables with arch values
-- Using 'tools.config.changePlatform' global function
local PKGDIR = changePlatform(arch)
tarball_files = ""
local add = function(f)
local tarball_files = ""
local metadata_files = ""
-- Adds file contents to a big string
local function add(f)
if f then
str = f:read("*a"):gsub("\n"," "):gsub("${TEC_UNAME}",arch)
local str = f:read("*a"):gsub("\n"," "):gsub("${TEC_UNAME}",arch)
tarball_files = tarball_files .. str
f:close()
end
end
local function addmetadata(filename)
if io.open(filename,"r") then
metadata_files = metadata_files .." ".. filename
end
end
local _,name = profile:match("(.*)/(.*)") --extracts name from "dir/name.profile"
local _,name = profile:match("(.*)/(.*)") --extracts name "dir/name.profile"
name = name or profile --could nil only if "name.profile"
name = name:gsub(".profile","") --deletes the suffix ".profile"