local createVersion = require('/apis/libversion');

local DEFAULT_CLOUD_URL = 'wss://os.trapcloud.fr';
local CLOUD_URL_SETTING = 'cloud.url';
local CLOUD_PASSWORD_SETTING = 'cloud.password';

local function isBlank(value)
  return type(value) ~= 'string' or value == '';
end

local function printUsage()
  print('trapos-postinstall usage:');
  print();
  print('\t\ttrapos-postinstall');
  print('\t\ttrapos-postinstall version');
  print('\t\ttrapos-postinstall help');
end

local command = ...;

if command == 'version' or command == '-version' or command == '--version' then
  print('v' .. createVersion().forSelf());
  return;
end

if command == 'help' or command == '-help' or command == '--help' then
  printUsage();
  return;
end

if command ~= nil and command ~= '' then
  printUsage();
  return;
end

local function readManifestVersion()
  if not fs.exists('/trapos/manifest.json') then return nil; end
  local f = fs.open('/trapos/manifest.json', 'r');
  if not f then return nil; end
  local data = f.readAll();
  f.close();
  local manifest = data and textutils.unserializeJSON(data);
  return manifest and manifest.version or nil;
end

local version = readManifestVersion();
local configuredCloudUrl = false;

if isBlank(settings.get(CLOUD_URL_SETTING)) then
  shell.run('set', CLOUD_URL_SETTING, DEFAULT_CLOUD_URL);
  configuredCloudUrl = true;
end

local hasCloudPassword = not isBlank(settings.get(CLOUD_PASSWORD_SETTING));

print();
if version then
  print('=> TrapOS v' .. version .. ' installed.');
else
  print('=> TrapOS installed.');
end
if configuredCloudUrl then
  print('=> Configured cloud.url to ' .. DEFAULT_CLOUD_URL .. '.');
else
  print('=> Keeping existing cloud.url.');
end
if hasCloudPassword then
  print('=> Cloud password already configured.');
else
  print('=> Cloud password not set.');
end
print();
print('Get started:');
print('  cloud --help    -- open the cloud help');
print('  trapos-upgrade    -- update and upgrade TrapOS');
print();
