#!/bin/bash

# Copyright: 2018 Dmitry Smirnov <onlyjob@member.fsf.org>
#            2021 Sophie Brun <sophie@offensive-security.com>
# License: GPL-3+
# This program 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.  .  This package 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  along with this
# program. If not, see <http://www.gnu.org/licenses/>.

set -e

if [ "$1" = '--upstream-version' ]; then
    new_version="$2"
else
    printf "Missing --upstream-version argument" 1>&2
    exit 1
fi

DEB_SOURCE="$(dpkg-parsechangelog -SSource)"
GIT_UPSTREAM_URL=https://github.com/securesocketfunneling/ssf

filename="$(readlink -f ../${DEB_SOURCE}_${new_version}.orig.tar.gz)"
current_dir=$(pwd)
echo ${current_dir}

work_dir="$(mktemp -d -t get-orig-source_${DEB_SOURCE}_${new_version}_XXXXXXX)"
trap "rm -rf '$work_dir'" EXIT

# create the structure directories
mkdir -p ${work_dir}/windows-binaries

# download the windows binaries
wget ${GIT_UPSTREAM_URL}/releases/download/${new_version}/ssf-win-i386-${new_version}.zip -O ${work_dir}/win-i386.zip
wget ${GIT_UPSTREAM_URL}/releases/download/${new_version}/ssf-win-x86_64-${new_version}.zip -O ${work_dir}/win-x86.zip

# unzip files
unzip ${work_dir}/win-i386.zip -d ${work_dir}/windows-binaries
unzip ${work_dir}/win-x86.zip -d ${work_dir}/windows-binaries

# remove version from directories names
mv ${work_dir}/windows-binaries/ssf-win-i386-${new_version} ${work_dir}/windows-binaries/ssf-win-i386
mv ${work_dir}/windows-binaries/ssf-win-x86_64-${new_version} ${work_dir}/windows-binaries/ssf-win-x86_64

echo "liste"
find ${work_dir}
# create tarball
tar -zcvf ../secure-socket-funneling_${new_version}.orig.tar.gz -C ${work_dir} windows-binaries

rm -rf $work_dir
