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

local function printUsage()
  print('trapos-create-disk usage:');
  print();
  print('\t\ttrapos-create-disk --install');
  print('\t\ttrapos-create-disk --reinstall');
  print('\t\ttrapos-create-disk --uninstall');
  print('\t\ttrapos-create-disk version');
  print('\t\ttrapos-create-disk help');
end

local function printColored(msg, color)
  if term.isColor and term.isColor() then
    local previous = term.getTextColor();
    term.setTextColor(color);
    print(msg);
    term.setTextColor(previous);
  else
    print(msg);
  end
end

local rawArgs = table.pack(...);

if rawArgs.n == 1 and (rawArgs[1] == 'version' or rawArgs[1] == '-version' or rawArgs[1] == '--version') then
  print('v' .. createVersion().forSelf());
  return;
end

if rawArgs.n == 0 or (rawArgs.n == 1 and (rawArgs[1] == 'help' or rawArgs[1] == '-help' or rawArgs[1] == '--help')) then
  printUsage();
  return;
end

local mode = nil;
local parseError = nil;

local function selectMode(nextMode)
  if mode and mode ~= nextMode then
    parseError = 'choose only one disk mode';
  else
    mode = nextMode;
  end
end

for i = 1, rawArgs.n do
  local arg = rawArgs[i];
  if arg == '--install' then
    selectMode('install');
  elseif arg == '--reinstall' then
    selectMode('reinstall');
  elseif arg == '--uninstall' then
    selectMode('uninstall');
  else
    parseError = 'unknown argument: ' .. tostring(arg);
  end
end

if parseError or not mode then
  if parseError then printColored(parseError, colors.red); end
  printUsage();
  return;
end

local ok, result = createInstallerDisk().create({ mode = mode });
if not ok then
  printColored(result, colors.red);
  return;
end

printColored('=> TrapOS ' .. mode .. ' disk created on ' .. result.name .. '.', colors.lime);
print('Label: ' .. result.label);
if result.settingsCopied then
  print('Cloned /.settings to ' .. fs.combine(result.mountPath, '.settings'));
elseif result.settingsWarning then
  printColored('Warning: /.settings not found; install disk has no cloned settings.', colors.orange);
end

if mode == 'install' then
  print('Insert this disk into a blank computer and reboot it.');
elseif mode == 'reinstall' then
  print('Insert this disk into the target computer and reboot it to reinstall TrapOS.');
else
  print('Insert this disk into the target computer and reboot it to remove TrapOS.');
end
