#!/usr/bin/env bash
###
 # Creates a compressed backup of the GitLab server instance.
 #
 # As per GitLab documentation, this does not include the "gitlab.rb" or "gitlab-secrets.json" files.
 # Those should be manually backed up and stored in a secure location.
 #
 #
 # Required Args:
 #  * Folder path to save backup data to.
 #
 # Optional Kwargs:
 #  * Backup User - Linux user to set as owner of backed up files. Assumes corresponding group of same name exists.
 #      * Accepted Kwargs: backup_user
 #
 # Optional Flags:
 #  * Delete Previous Backups - Clear existing files from backup folders prior to creating new backups.
 #      * Accepted Flags: d / delete_previous_backups / delete_prev_backups / delete_prev
 #
 #
 # https://git.brandon-rodriguez.com/scripts/bash/server_management
 # Version 1.0
 ##


# Define possible flag values for script.
possible_flags=("-d" "-delete_previous_backups" "-delete_prev_backups" "-delete_prev")


# Import utils script.
. $(dirname ${0})/../utils.sh


# Stop on error.
set -e


# Global Variables.
backup_location=""
current_date=`date +%Y-%m-%d`
gitlab_backup_location="/var/opt/gitlab/backups"
backup_user="backups"


###
 # Script entry point.
 ##
function main () {

    # Verify running as root user.
    check_is_user "root"

    # Check for provided args.
    validate_args

    # Attempt backup.
    backup_gitlab
}


###
 # Validate provided script args.
 ##
function validate_args () {

    # Check for minimum number of args.
    if [[ ${#args[@]} < 1 ]]
    then
        echo -e "${text_red}Missing arg. Requires location to backup gitlab to.${text_reset}"
        exit 0
    elif [[ ${#args[@]} > 1 ]]
    then
        echo -e "${text_red}Too many args provided. Requires location to backup gitlab to.${text_reset}"
        exit 0
    fi

    # Grab args.
    get_absolute_path "${args[0]}"
    backup_location="${return_value}"

    # Check up for backup location arg.
    if [[ ${backup_location} == "" || ! -d ${backup_location} ]]
    then
        echo -e "${text_red}Must provide valid directory as first argument for \"backup_location\".${text_reset}"
        echo -e "${text_red}Please verify the location exists, and that the location points to a folder, not a file.${text_reset}"
        exit 0
    fi

    # Check for backup user kwarg.
    if [[ "${!kwargs[@]}" =~ "backup_user" ]]
    then
        backup_user="${kwargs[backup_user]}"
    fi
}


###
 # Logic to backup gitlab instance.
 ##
function backup_gitlab () {

    echo -e "${text_blue}Attempting to backup GitLab data.${text_reset}"
    echo ""

    # Check for "delete previous backups" flags.
    if [[ ${flags[@]} =~ "d" || ${flags[@]} =~ "delete_previous_backups" || ${flags[@]} =~ "delete_prev_backups" || ${flags[@]} =~ "delete_prev" ]]
    then
        echo "Clearing out old gitlab backups."

        # Clear any old backup files from gitlab backup folder.
        for file in "${gitlab_backup_location}/"*
        do
            # Verify is file.
            if [[ -f "${file}" ]]
            then
                rm "${file}"
            fi
        done

        # Clear any old backup files from indicated backup folder.
        for file in "${backup_location}/"*
        do
            # Verify is file.
            if [[ -f "${file}" ]]
            then
                rm "${file}"
            fi
        done

        echo "Old backups removed."
        echo ""
    fi

    # Tell gitlab server to create backups.
    echo "Creating server backup. This may take a bit."
    gitlab-backup create

    # Attempt to move backup files to more accessible location.
    for file in "${gitlab_backup_location}/"*
    do
        # Verify if file.
        if [[ -f "${file}" ]]
        then
            # Get gitlab version of backup.
            # Start by getting full file name of file, minus directory info.
            file_name=${file##*/}
            # Remove extension info. We know it will be ".tar".
            file_name=${file_name%.*}
            # Remove extra file info on right side of file name.
            ver_num=${file_name%_*}
            ver_num=${ver_num%_*}
            # Remove extra file info on left side of file name.
            ver_num=${ver_num#*_}
            ver_num=${ver_num#*_}
            ver_num=${ver_num#*_}
            ver_num=${ver_num#*_}

            # Update file permissions.
            chown "${backup_user}":"${backup_user}" ${file}
            chmod o-rwx ${file}


            # Move file to backup location.
            mv "${file}" "${backup_location}/${ver_num}__${current_date}.tar"
        fi
    done

    echo ""
    echo -e "${text_blue}Gitlab Instance backed up to \"${backup_location}/${ver_num}__${current_date}.tar\".${text_reset}"
}


main
