<%=

def install_dependencies
  script = ''

  script += <<-INSTALL
    test ! -e "$(dirname $0)/formula-fetch.sh" || . "$(dirname $0)/formula-fetch.sh"
    test ! -e "$(dirname $0)/repository-setup.sh" || . "$(dirname $0)/repository-setup.sh"

    export SALT_ROOT="#{config[:root_path]}/#{config[:salt_file_root]}";
    export SALT_SHARE_DIR='/usr/share/salt-formulas'
    export DEBIAN_FRONTEND=noninteractive

    mkdir -p "${SALT_ROOT}";
    mkdir -p "${SALT_SHARE_DIR}";
  INSTALL


  # setup apt
  config[:vendor_repo].select{|x| x[:type]=='apt'}.each do |repo|
    id  =repo[:url].gsub(/[htp:\/.]/,'')
    arch=repo[:arch] || '[arch=amd64]'
    rurl=repo[:url]
    comp=repo[:components] || 'main'
    dist=repo[:distribution] || '$DISTRIB_CODENAME'
    rkey=repo[:key_url]
    script += <<-INSTALL
      apt_repo_add "#{id}" "#{arch}" "#{rurl}" "#{comp}" "#{dist}" "#{rkey}";
    INSTALL
  end

  # setup ppa
  config[:vendor_repo].select{|x| x[:type]=='ppa'}.each do |repo|
    script += <<-INSTALL
        add-apt-repository "ppa:#{repo[:name]}" -y;
    INSTALL
  end

  # TODO, setup yum repo

  # update resources
  config[:vendor_repo].map{|x| x[:type]}.uniq.each do |type|
    case type
    when 'apt'
      script += <<-INSTALL
        apt-get update -q;
        sleep 10;
      INSTALL
    when 'yum'
      script += <<-INSTALL
        yum update;
        sleep 10;
      INSTALL
    when 'spm'
      script += <<-INSTALL
        spm update_repo;
      INSTALL
    end
  end

  # install formulas
  config[:dependencies].each do |formula|
    if formula.key?(:repo)
      case formula[:repo]
      when 'git'
        script += <<-INSTALL
          fetchGitFormula #{formula[:source]} "#{formula[:name]}" "#{formula[:branch] || 'master'}"
        INSTALL
      when 'spm'
        if formula[:package].nil?
          script += <<-INSTALL
          spm -c #{config[:root_path]}/etc/salt install -y #{formula[:name]};
          INSTALL
        else
          script += <<-INSTALL
            curl -O #{formula[:package]};
            spm -c #{config[:root_path]}/etc/salt local install -y "$(basename #{formula[:package]})";
          INSTALL
        end
      when 'yum'
        script += <<-INSTALL
          yum install -y #{formula[:package]||formula[:name]};
        INSTALL
      when 'apt'
        script += <<-INSTALL
          apt-get install -y #{formula[:package]||formula[:name]};
        INSTALL
      end
    elsif formula.key?(:path)
      prepare_formula formula[:path], formula[:name]
    end
  end
  script += <<-INSTALL
    linkFormulas "$SALT_ROOT"
    chown -R "${SUDO_USER:-$USER}" "${SALT_SHARE_DIR}" "${SALT_ROOT}";
    echo "Content of $SALT_ROOT :";
    ls -la "$SALT_ROOT";
  INSTALL
  return script
end


<<-INSTALL
#!/usr/bin/env bash

echo "Install External Dependencies";
#{install_dependencies}

INSTALL
%>
