# frozen_string_literal: true

ROOT = '/opt/zammad'

def _read_file(file, fullpath: false)
  location = case fullpath
             when false
               "#{ROOT}/#{file}"
             when true
               file
             else
               "#{fullpath}/#{file}"
             end
  File.binread(location)
end

def _write_file(file, permission, data)
  location = "#{ROOT}/#{file}"

  # rename existing file if not already the same file
  if File.exist?(location)
    content_fs = _read_file(file)
    if content_fs == data
      puts { "NOTICE: file '#{location}' already exists, skip install" }
      return true
    end
    backup_location = "#{location}.save"
    puts "NOTICE: backup old file '#{location}' to #{backup_location}"
    File.rename(location, backup_location)
  end

  # check if directories need to be created
  directories = location.split '/'
  (0..(directories.length - 2)).each do |position|
    tmp_path = ''
    (1..position).each do |count|
      tmp_path = "#{tmp_path}/#{directories[count]}"
    end

    next if tmp_path == ''
    next if File.exist?(tmp_path)

    Dir.mkdir(tmp_path, 0o755)
  end

  # install file
  puts "NOTICE: install '#{location}' (#{permission})"
  file = File.new(location, 'wb')
  file.write(data)
  file.close
  File.chmod(permission.to_s.to_i(8), location)
  true
end

def install(data)
  json = _read_file(data, fullpath: true)
  package = JSON.parse(json)
  package['files'].each do |file|
    permission = file['permission'] || '644'
    content    = Base64.decode64(file['content'])
    _write_file(file['location'], permission, content)
  end
end

def install_all
  packages = Dir.glob('/opt/zammad/contrib/link/addons/*')
  packages.each do |package|
    puts "Installing #{package} package..."
    install(package)
    puts 'Installed'
  rescue StandardError => e
    puts e.message
  end
end

puts 'Installing packages...'
install_all
