#!/bin/sh
set -e
# 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

mkdir -p ${diaspora_cache}

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

echo "Checking integrity of download..."
sha256sum -c ${diaspora_sha256sums}

echo "Extracting files..."
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}"

# 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 --exclude .yarn --exclude yarn.lock
su diaspora -s /bin/sh -c "cp -r  ${diaspora_cache}/${diaspora_archive}/app/assets/* ${diaspora_user_home}/app-assets"
su diaspora -s /bin/sh -c "cp -r  ${diaspora_cache}/${diaspora_archive}/public/* ${diaspora_user_home}/public"
su diaspora -s /bin/sh -c "cp ${diaspora_cache}/${diaspora_archive}/yarn.lock ${diaspora_user_home}"
ln -sf ${diaspora_user_home}/yarn.lock ${diaspora_home}

# 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
