#!/bin/bash

# Copyright (c) 2019 SUSE Linux GmbH
#
# This file is part of susemanager-cloud-setup.
#
# susemanager-cloud-setup is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# susemanager-cloud-setup is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License

. /usr/lib/susemanager/bin/susemanager-cloud-setup-functions.sh || exit 1

case "$1" in
  "-h"|"--help"|"")
    usage
    ;;
esac

if [ ! $UID = 0 ];then
    die "You must be root to run this script."
fi

storage_disk=$(linux_device $1)
storage_fs=xfs
storage_location="/manager_storage"

if [ -z "$storage_disk" ] || [ ! -b "$storage_disk" ];then
    usage
    die "Given storage disk does not exist or is not a block device."
fi

info "Check disk for content signature"
check_content_signature $storage_disk

info "Creating partition on disk $storage_disk"
create_partition $storage_disk

info "Creating $storage_fs filesystem"
create_filesystem $storage_disk $storage_fs

info "Mounting storage at $storage_location"
mount_storage $storage_disk $storage_location

info "Syncing SUSE Manager Server directories to storage disk"
move_storage /var/lib/spacewalk $storage_location 
move_storage /var/lib/pgsql $storage_location 
if [ -d /var/spacewalk/packages ]; then
    # copy package storage
    move_storage /var/spacewalk ${storage_location}/spacewalk
else
    # no packages stored yet, just create the link
    ln -s ${storage_location}/spacewalk /var/spacewalk
fi

info "Creating entry in /etc/fstab"
update_fstab $storage_disk $storage_location

exit 0
