#!/usr/bin/env ruby
# encoding: UTF-8

require 'fileutils'

raise 'Never run this script as root!' if `id -u`.chomp == '0'

STEAM_DIST_NAME = 'steam_1.0.0.79.tar.gz'

SHA256 = {
  'steam_1.0.0.79.tar.gz': '3a0012daf5889311c2e1dcf33a587b409019b66d893a52192df6947e18f1ec46'
}

DUMB_PERSON_FLAG = '--allow-stealing-my-passwords,-browser-history-and-ssh-keys'
skip_sanity_check = ARGV.include?(DUMB_PERSON_FLAG)

if !skip_sanity_check && `id -G`.split(' ').include?('0')
  STDERR.puts <<MSG

Please, consider setting up a dedicated OS user account for Steam.
Otherwise each and every Steam game will have unrestricted access to your files.
If you really couldn't care less, you can supress this message with
#{DUMB_PERSON_FLAG} flag.

MSG
  exit(1)
end

def set_up_file(path)
  if not File.exist?(path)
    yield path
    if not File.exist?(path)
      raise "Failed to create/download #{path}"
    end
  end
end

def verify_checksum(path)
  if `sha256 -q #{path}`.chomp != SHA256[File.basename(path).to_sym]
    raise "#{path} failed integrity check"
  end
end

steam_root = File.join(ENV['HOME'], '.steam')
FileUtils.mkdir_p(steam_root)

Dir.chdir(steam_root) do

  set_up_file('steam/ubuntu12_32') do

    set_up_file(STEAM_DIST_NAME) do
      STDERR.puts 'Downloading Steam...'
      system("fetch http://repo.steampowered.com/steam/pool/steam/s/steam/#{STEAM_DIST_NAME} || fetch http://repo.steampowered.com/steam/archive/stable/#{STEAM_DIST_NAME}")
    end

    verify_checksum(STEAM_DIST_NAME)

    FileUtils.mkdir_p('steam')

    STDERR.puts 'Extracting bootstrap...'
    system("tar -xf #{STEAM_DIST_NAME} --strip-components 1 --to-stdout steam-launcher/bootstraplinux_ubuntu12_32.tar.xz | tar -C steam -xf -")
  end

  for symlink, target in {
    'root'    => 'steam',
    'bin32'   => 'steam/ubuntu12_32',
    'bin64'   => 'steam/ubuntu12_64',
    'sdk32'   => 'steam/linux32',
    'sdk64'   => 'steam/linux64',
  }
    if not File.symlink?(symlink)
      STDERR.puts "Creating symlink #{symlink} -> #{target}"
      FileUtils.ln_s(target, symlink)
    end
  end
end # ~/.steam

STDERR.puts "You can run #{File.join(__dir__, 'steam')} now."
