#!/bin/bash
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

debDir="deb_files"

rm -f deb_info.txt
rm -f debFiles.txt
rm -f sortedDebs.txt

# Create the paackage information file for further processing by Python
ls $debDir/*.deb | sed -e 's~deb_files/~~' > debFiles.txt


for i in `cat debFiles.txt`
do
	pkgName=""
	deps=""
	pkgName=`dpkg -I $debDir/$i | egrep "^[ ]*Package:" | sed -e 's/Package://' | sed -e 's/\([ ]\+\)\|\([ ]\+$\)//'`
	deps=`dpkg -I $debDir/$i | grep Depends: | sed -e 's/Depends://' | sed -e 's/\([ ]\+\)\|\([ ]\+$\)//'`
	deps=`echo $deps | sed -e 's/|/,/g' | sed -e 's/([^)]\+)//g' | sed -e 's/:any//g' | sed -e 's/,//g'`
	deps=`echo $deps | sed -e 's/[ ]\+/ /g' |  sed -e 's/\(^[ ]\+\)\|\([ ]\+$\)//' | sed -e 's/ /,/g'`
	#deps=`echo $deps | sed -e 's/^\(.\)/"\1/' | sed -e 's/\(.\)$/\1"/' | sed -s 's/,/","/g'`
	echo "${pkgName}:${i}:${deps}" >> deb_info.txt
done
rm -f debFiles.txt

# Now launch the python scrip that sorts the files based on the dependencies.
./sort_packages.py > sortedDebs.txt

rm -f deb_info.txt
