#!/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


usage() {
    echo "Usage: $0 <storage-disk-device>"
    echo
}

case "$1" in
  "-h"|"--help"|"")
    usage
    exit 0
    ;;
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 "Checking 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

if systemctl status squid.service >/dev/null ; then
    squid_running=yes
    info "Stopping squid service"
    systemctl stop squid.service
fi

info "Syncing SUSE Manager Proxy directories to storage disk"
move_storage /var/cache/squid $storage_location 

if [ "$squid_running" = "yes" ]; then
    info "Starting squid service"
    systemctl start squid.service
fi

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

exit 0
