#!/bin/sh

# Source variables
. /etc/diaspora/diaspora-common.conf

echo "Download diaspora tarball version ${diaspora_version} from github.com..."

# Downloading a branch and tag is supported
if test ${diaspora_release_type} = "branch"
then
    export diaspora_archive="diaspora-release-${diaspora_version}"
else
    export diaspora_archive="diaspora-${diaspora_version}"
fi

chown ${diaspora_user}: ${diaspora_cache}
chown ${diaspora_user}: ${diaspora_user_home}

# Skip download if already present
if ! test -f ${diaspora_cache}/diaspora-${diaspora_version}.tar.gz
then 
    if test ${diaspora_release_type} = "branch"
    then
	su  ${diaspora_user} -s /bin/sh -c "wget -O ${diaspora_cache}/diaspora-${diaspora_version}.tar.gz ${github_archive_url}/release/${diaspora_version}.tar.gz"
    else
        su  ${diaspora_user} -s /bin/sh -c "wget -O ${diaspora_cache}/diaspora-${diaspora_version}.tar.gz ${github_archive_url}/v${diaspora_version}.tar.gz"
    fi
fi

echo "Checking integrity of download..."
su  ${diaspora_user} -s /bin/sh -c "sha256sum -c ${diaspora_sha256sums}"

echo "Extracting files..."
su  ${diaspora_user} -s /bin/sh -c "tar -C ${diaspora_cache} -zxvf ${diaspora_cache}/diaspora-${diaspora_version}.tar.gz >/dev/null"
    
echo "Copying files to ${diaspora_home}..."
    
echo "diaspora archive to copy: ${diaspora_archive}"

su  ${diaspora_user} -s /bin/sh -c "mkdir -p ${diaspora_user_home}/public"
su  ${diaspora_user} -s /bin/sh -c "mkdir -p ${diaspora_user_home}/app-assets"

# Exclude user generated or files or directories
rsync -a ${diaspora_cache}/${diaspora_archive}/* ${diaspora_home} --exclude tmp --exclude log --exclude db/schema.rb --exclude app/assets --exclude public --exclude config/oidc_key.pem
su  ${diaspora_user} -s /bin/sh -c "cp -r  ${diaspora_cache}/${diaspora_archive}/app/assets/* ${diaspora_user_home}/app-assets"
su  ${diaspora_user} -s /bin/sh -c "cp -r  ${diaspora_cache}/${diaspora_archive}/public/* ${diaspora_user_home}/public"
cp -r  ${diaspora_cache}/${diaspora_archive}/config/* /etc/diaspora

echo "Applying patches..."
patch -p2 -t -d config -i /usr/share/diaspora-installer/patches/set-rails-root.patch

# Remove BUNDLED WITH from Gemfile.lock to allow using packaged bundler
head -n -3 ${diaspora_cache}/${diaspora_archive}/Gemfile.lock > ${diaspora_home}/Gemfile.lock

echo "Copying source tarball to ${diaspora_user_home}/public..."
cp -f ${diaspora_cache}/diaspora-${diaspora_version}.tar.gz ${diaspora_user_home}/public/source.tar.gz
