# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/. -}

GCC_VERSION = "14.2.0"

TMP = Pathname.new('./build')

class BuildTarget
  attr_accessor(:build, :gcc, :target, :tmp)

  def gxx
    @gcc.gsub 'c', '+'
  end

  def sysroot
    tmp + 'sysroot'
  end

  def rootfs
    tmp + 'rootfs'
  end

  def tools
    tmp + 'tools'
  end

  def configuration
    case target
    when /^riscv[[:digit:]]+-/
      [
        '--with-arch=rv32imafdc',
        '--with-abi=ilp32d',
        '--with-tune=rocket',
        '--with-isa-spec=20191213'
      ]
    else
      []
    end
  end
end

def gcc_verbose(gcc_binary)
  read, write = IO.pipe
  sh({'LANG' => 'C'}, gcc_binary, '--verbose', err: write)
  write.close
  output = read.read
  read.close
  output
end

def find_build_target(gcc_version, target)
  gcc_binary = 'gcc'
  output = gcc_verbose gcc_binary

  if output.start_with? 'Apple clang'
    gcc_binary = "gcc-#{gcc_version.split('.').first}"
    output = gcc_verbose gcc_binary
  end
  result = output
    .lines
    .each_with_object(BuildTarget.new) do |line, accumulator|
      if line.start_with? 'Target: '
        accumulator.build = line.split(' ').last.strip
      elsif line.start_with? 'COLLECT_GCC'
        accumulator.gcc = line.split('=').last.strip
      end
    end
  result.tmp = TMP
  result.target = target
  result
end