ActiveAdmin.register_page "Bootstrap"  do
  menu :parent => 'Icecast'

  page_action :create_server, :method => :post do

    template = IcecastTemplate.find_by_id(params[:jam_ruby_icecast_server][:template_id])
    mount_template = IcecastMountTemplate.find_by_id(params[:jam_ruby_icecast_server][:mount_template_id])
    hostname = params[:jam_ruby_icecast_server][:hostname]

    server = IcecastServer.new
    server.template = template
    server.mount_template = mount_template
    server.hostname = hostname
    server.server_id = hostname
    server.save!

     redirect_to admin_bootstrap_path, :notice => "Server created.  If you start a job worker (bundle exec rake all_jobs in /web), it should update your icecast config."
  end

  page_action :brew_template, :method => :post do
    # to make this template, I just did 'brew install icecast', and then based  the rest of this code on what I saw in /usr/local/etc/icecast.xml


    IcecastServer.transaction do


      limit = IcecastLimit.new
      limit.clients         = 100
      limit.sources         = 2
      limit.queue_size      = 524288
      limit.client_timeout  = 30
      limit.header_timeout  = 15
      limit.source_timeout  = 10
      limit.burst_size      = 65535
      limit.save!

      admin_auth = IcecastAdminAuthentication.new
      admin_auth.source_pass      = 'blueberryjam'
      admin_auth.relay_user       = 'jamjam'
      admin_auth.relay_pass       = 'blueberryjam'
      admin_auth.admin_user       = 'jamjam'
      admin_auth.admin_pass       = 'blueberryjam'
      admin_auth.save!

      path = IcecastPath.new
      path.base_dir               = '/usr/local/Cellar/icecast/2.4.1/share/icecast'
      path.log_dir                = '/usr/local/Cellar/icecast/2.4.1/var/log/icecast'
      path.web_root               = '/usr/local/Cellar/icecast/2.4.1/share/icecast/web'
      path.admin_root             = '/usr/local/Cellar/icecast/2.4.1/share/icecast/admin'
      path.pid_file               = nil
      path.save!

      security = IcecastSecurity.new
      security.chroot             = false
      security.save!

      logging = IcecastLogging.new
      logging.access_log          = 'access.log'
      logging.error_log           = 'error.log'
      logging.log_level           = 3 # you might want to change this after creating the template
      logging.log_size            = 10000
      logging.save!

      listen_socket1 = IcecastListenSocket.new
      listen_socket1.port         = 10000
      listen_socket1.save!

      listen_socket2 = IcecastListenSocket.new
      listen_socket2.port         = 10001
      listen_socket2.save!

      template = IcecastTemplate.new
      template.name               = "Brew-#{IcecastTemplate.count + 1}"
      template.location           = '@work'
      template.admin_email        = 'nobody@jamkazam.com'
      template.fileserve          = true
      template.limit              = limit
      template.admin_auth         = admin_auth
      template.path               = path
      template.security           = security
      template.logging            = logging
      template.listen_sockets     = [listen_socket1, listen_socket2]
      template.save!
    end

    redirect_to admin_bootstrap_path, :notice => "Brew template created.  Now, create a mount template."
  end

  page_action :ubuntu_template, :method => :post do
    # to make this template, I installed icecast233 from jenkins (or our chef'ed apt-repo, same difference), and then based  the rest of this code on what I saw in /etc/icecast2/icecast.xml

    IcecastServer.transaction do

      limit = IcecastLimit.new
      limit.clients         = 100
      limit.sources         = 2
      limit.queue_size      = 524288
      limit.client_timeout  = 30
      limit.header_timeout  = 15
      limit.source_timeout  = 10
      limit.burst_size      = 65535
      limit.save!

      admin_auth = IcecastAdminAuthentication.new
      admin_auth.source_pass      = 'blueberryjam'
      admin_auth.relay_user       = 'jamjam'
      admin_auth.relay_pass       = 'blueberryjam'
      admin_auth.admin_user       = 'jamjam'
      admin_auth.admin_pass       = 'blueberryjam'
      admin_auth.save!
      path = IcecastPath.new
      path.base_dir               = '/usr/share/icecast2'
      path.log_dir                = '/var/log/icecast2'
      path.web_root               = '/usr/share/icecast2/web'
      path.admin_root             = '/usr/share/icecast2/admin'
      path.pid_file               = nil
      path.save!

      security = IcecastSecurity.new
      security.chroot             = false
      security.save!

      logging = IcecastLogging.new
      logging.access_log          = 'access.log'
      logging.error_log           = 'error.log'
      logging.log_level           = 3 # you might want to change this after creating the template
      logging.log_size            = 10000
      logging.save!

      listen_socket1 = IcecastListenSocket.new
      listen_socket1.port         = 10000
      listen_socket1.save!

      listen_socket2 = IcecastListenSocket.new
      listen_socket2.port         = 10001
      listen_socket2.save!

      template = IcecastTemplate.new
      template.name               = "Ubuntu-#{IcecastTemplate.count + 1}"
      template.location           = '@work'
      template.admin_email        = 'nobody@jamkazam.com'
      template.fileserve          = true
      template.limit              = limit
      template.admin_auth         = admin_auth
      template.path               = path
      template.security           = security
      template.logging            = logging
      template.listen_sockets     = [listen_socket1, listen_socket2]
      template.save!
    end

    redirect_to admin_bootstrap_path, :notice => "Ubuntu 12.04 template created.  You should also install the icecast233 package:  https://int.jamkazam.com/jenkins/job/icecast-debian/"
  end

  page_action :create_mount_template, :method => :post do
    IcecastServer.transaction do
      hostname = params[:jam_ruby_icecast_mount_template][:hostname]
      type = params[:jam_ruby_icecast_mount_template][:default_mime_type]

      auth = IcecastUserAuthentication.new
      auth.authentication_type = 'url'
      auth.mount_add = 'http://' + hostname + '/api/icecast/mount_add'
      auth.mount_remove = 'http://' + hostname + '/api/icecast/mount_remove'
      auth.listener_add = 'http://' + hostname + '/api/icecast/listener_add'
      auth.listener_remove = 'http://' + hostname + '/api/icecast/listener_remove'
      auth.auth_header = 'HTTP/1.1 200 OK'
      auth.timelimit_header = 'icecast-auth-timelimit:'
      auth.save!

      mount_template = IcecastMountTemplate.new
      mount_template.name                     = "#{type}-#{IcecastMountTemplate.count + 1}"
      mount_template.source_username          = nil # mount will override
      mount_template.source_pass              = nil # mount will override
      mount_template.max_listeners            = 20000 # huge
      mount_template.max_listener_duration    = 3600 * 24 # one day
      mount_template.fallback_override        = 1
      mount_template.fallback_when_full       = 1
      mount_template.is_public                = 0
      mount_template.stream_name              = nil # mount will override
      mount_template.stream_description       = nil # mount will override
      mount_template.stream_url               = nil # mount will override
      mount_template.genre                    = nil # mount will override
      mount_template.bitrate                  = 128
      mount_template.burst_size               = 65536
      mount_template.hidden                   = 1
      mount_template.on_connect               = nil
      mount_template.on_disconnect            = nil
      mount_template.authentication           = auth

      if type == 'ogg'
        mount_template.mp3_metadata_interval    = nil
        mount_template.mime_type                ='audio/ogg'
        mount_template.subtype                  = 'vorbis'
        #mount_template.fallback_mount           = "/fallback-#{mount_template.bitrate}.ogg"
      else
        mount_template.mp3_metadata_interval    = 4096
        mount_template.mime_type                ='audio/mpeg'
        mount_template.subtype                  = nil
        #mount_template.fallback_mount           = "/fallback-#{mount_template.bitrate}.mp3"
      end
      mount_template.save!
    end

    redirect_to admin_bootstrap_path, :notice => "Mount template created.  Create a server now with your new templates specified."
  end


  action_item do
    link_to "Create MacOSX (Brew) Template", admin_bootstrap_brew_template_path, :method => :post
  end

  action_item do
    link_to "Create Ubuntu 12.04 Template", admin_bootstrap_ubuntu_template_path, :method => :post
  end


  content do

    if IcecastTemplate.count == 0
      para "You need to create at least one server template, and one mount template.  Click one of the top-left buttons based on your platform"

    elsif IcecastMountTemplate.count == 0
      active_admin_form_for IcecastMountTemplate.new, :url => admin_bootstrap_create_mount_template_path, :builder => ActiveAdmin::FormBuilder do |f|
        f.inputs "New Mount Template" do
          f.input :hostname, :label => "jam-web public hostname:port (such that icecast can reach it)"
          f.input :default_mime_type, :as => :select, :collection => ["ogg", "mp3"]
        end
        f.actions
      end
    else
      active_admin_form_for IcecastServer.new, :url => admin_bootstrap_create_server_path, :builder => ActiveAdmin::FormBuilder do |f|
        f.inputs "New Icecast Server" do
          f.input :hostname, :hint => "Just the icecast hostname; no port"
          f.input :template, :hint => "This is the template associated with the server.  Not as useful for the 1st server, but subsequent servers can use this same template, and share config"
          f.input :mount_template, :hint => "The mount template. When mounts are made as music sessions are created, this template will satisfy templatable values"
        end
        f.actions
      end
    end

  end
end
