#!/usr/bin/env ruby # Copyright, 2015, by Samuel G. D. Williams. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'etc' # Add the following into sudoers for this to work correctly: # Users in group wheel can execute all commands as user http with no password. # %wheel ALL=(http) NOPASSWD: ALL GIT_WORK_TREE = `git config core.worktree`.chomp # We convert GIT_DIR to an absolute path: ENV['GIT_DIR'] = File.join(Dir.pwd, ENV['GIT_DIR']) # We deploy the site as the user and group of the directory for the working tree: File.stat(GIT_WORK_TREE).tap do |stat| ENV['DEPLOY_USER'] = DEPLOY_USER = Etc.getpwuid(stat.uid).name ENV['DEPLOY_GROUP'] = DEPLOY_GROUP = Etc.getgrgid(stat.gid).name end WHOAMI = `whoami`.chomp! # We should find out if we need to use sudo or not: SUDO = if WHOAMI != DEPLOY_USER ["sudo", "-u", "DEPLOY_USER"] end def sh(command) puts command.join(' ') system(*command) or abort("Deployment failed!") end def sudo(command) sh([*SUDO, *command]) end puts "Deploying to #{GIT_WORK_TREE} as #{DEPLOY_USER}:#{DEPLOY_GROUP}..." Dir.chdir(GIT_WORK_TREE) do # Pass on our rights to the files we just uploaded to the deployment user/group: sh %W{chmod -Rf ug+rwX .} sh %W{chown -Rf #{DEPLOY_USER}:#{DEPLOY_GROUP} .} sudo %W{git checkout -f} sudo %W{git submodule update -i} if File.exist? 'Gemfile' sudo %W{bundle install --deployment --clean --jobs=4 --retry=2 --quiet} end if File.exist? 'Rakefile' sudo %W{bundle exec rake deploy} end puts "Restarting server..." sudo %W{mkdir -p tmp} unless File.exist?('tmp') sudo %W{touch tmp/restart.txt} end